MaMu
MaMu

Reputation: 1869

Segfault - invalid pointer

I'm attaching a snippet. I have ommitted a lot. If needed I will attach more:

 unsigned char *datap = malloc (MAXSIZE);
 unsigned char *datapor = datap;
 //Here Im cutting a lot
 while( (direntp = readdir(dirp)) != NULL)
 {
   datap = datapor;
 }
//this line gives me exception 
free(datap);

gcc shows:

*** glibc detected *** /home/xf/xf/unzipper: free(): invalid pointer: 0x00002aaaab0b0108 ***

Upvotes: 0

Views: 511

Answers (2)

Zodoh
Zodoh

Reputation: 100

Your malloc could have fail because of the macro MAXSIZE. If you have not enough memory this could fail.

Start to check if datap = malloc(MAXSIZE) is a viable pointer.

unsigned char *datap = malloc (MAXSIZE);
if (datap == NULL)
    return -1; //malloc failed

Upvotes: 0

Klas Lindbäck
Klas Lindbäck

Reputation: 33273

You reassign datap in your while loop, so when you call free, datap no longer points to the allocated memory.

(I am assuming that the value of datapor changes in the omitted code.)

Upvotes: 2

Related Questions