Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

DYNAMIC MEMORY Error in : realloc(): invalid pointer: *** Aborted (core dumped)

c help dynamic memory realloc

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1 fdzcampos

fdzcampos

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 19 December 2015 - 12:27 PM

So the function I am working with is part of a bigger project (checkers game).What I am trying to do is save memory for 4 variables type char, and save more memory as the game progresses.

I am using malloc for the initial allocation of memory and then realloc to save more.

 

When I execute it I get this error:

Error in `./damas': realloc(): invalid pointer: 0x00007ffec3209fe7 ***
Aborted (core dumped)

void list(char *pcolumn_init,char *pcolumn_move,
        char *pline_init,char *pline_move,int *pturn)
{
    int res=5;
    char *lista,*temp;

    if(*pturn==1){
        temp=(char *)malloc(res*(sizeof(char)));
        if(!temp)
            printf("Could not save memory\n");

        temp[0]=*pline_init;
        temp[1]=*pcolumn_init;
        temp[2]=*pline_move;
        temp[3]=*pcolumn_move;
    }else{
        res+=4;
        lista=realloc(temp,res*sizeof(char));
        temp=lista;
        if(lista==NULL)
            free(temp);
                
        lista[res-4]=*pline_init;
        lista[res-3]=*pcolumn_init;
        lista[res-2]=*pline_move;
        lista[res-1]=*pcolumn_move;
    }       
}

If someone could help me fix this and understand what I am doing wrong


Edited by dargueta, 21 December 2015 - 10:52 PM.


#2 dargueta

dargueta

    I chown trolls.

  • Moderator
  • 4854 posts

Posted 21 December 2015 - 10:54 PM

1) After your printf call with "Could not save memory" you need to return. Right now you're printing an error message and then continuing to use the null pointer.

2) Your actual problem is when list() is called and pturn is not equal to 1. You never initialize temp, so when you try to reallocate it it explodes. Initialize temp with NULL and the realloc() call will work. (That only works because calling realloc() with a null pointer makes it behave like malloc()).


Edited by dargueta, 23 December 2015 - 01:33 AM.
Formatting

sudo rm -rf / && echo $'Sanitize your inputs!'