mik
mik

Reputation: 73

Invalid Pointer when freeing memory

I have a structure

typedef struct
{
    char **changeTime;  // Array of pointers
} r;

Size variables are as under

int SIZE = 10;
int BYTES = 1000;

Here I allocate memory

r.change_time = (char **) malloc(sizeof(char *) * SIZE);
for(i = 0 ; i < 10; i++)
    r.changeTime[x] = (char *) malloc(sizeof(char) * BYTES);

Lot of things happen

Finally I free memory

for(i = 0 ; i < 10; i++)
{
    if(r.changeTime[x] != NULL)
    {
        free(r.changeTime[x]);   <- Fails here
        r.changeTime[x] = NULL;  
    }
}

and finally

if(r.change_time != NULL)
{
    free(r.change_time)
    r.change_time = NULL;
}

Now, the code is failing at line mentioned above

I debugged using GDB. Here is the output

> *** glibc detected *** XYZ: free(): invalid pointer: 0x0000000006b61021 ***
> ======= Backtrace: ========= /lib64/libc.so.6[0x3e1b07247f] /lib64/libc.so.6(cfree+0x4b)[0x3e1b0728db]
> /panther/disk/libxc.so(free_record+0x1a)[0x2b303aadf44a]
> /panther/disk/libxc.so(MW_free+0x33)[0x2b303aadf413]
> /panther/disk/libxc.so(M1_free+0x1f)[0x2b303171a8cf]
> /panther/disk/libxc.so(M_free+0x12)[0x2b3030f91122]
> /panther/disk/libxc.so(term+0x34)[0x2b3027e4e294]
> /panther/disk/libxc.so(proc+0x8c)[0x2b3027e5252c]
> /panther/disk/libxc.so(main+0x5dd)[0x2b3027e3d79d]

Please help !!

Upvotes: 2

Views: 760

Answers (3)

AnT stands with Russia
AnT stands with Russia

Reputation: 320679

Your cycles use i as iterator variable. But your array access inside the cycle uses x as an index for some reason

for(i = 0 ; i < 10; i++)
    r.changeTime[x] = (char *) malloc(sizeof(char) * BYTES);

What on Earth is x and what is it doing there? You are lucky if x is in [0, 10) range.

And in any case, allocating memory 10 times and storing the pointer in the same r.changeTime[x] turns 9 of those 10 allocations into memory leaks.

Later you attempt to deallocate the same r.changeTime[x] ten times. If at that point x is out of range, then it expectedly triggers this error.

Upvotes: 2

Nishant
Nishant

Reputation: 1665

*** glibc detected *** XYZ: free(): invalid pointer: 0x0000000006b61021 ***

This line states that, the pointer you are trying to delete is not valid, the part of the code, where you are saying lot of things happen, you must have changed the value of changeTime, you would have made it point to something else, than the originally allocated memory.

Upvotes: 0

Employed Russian
Employed Russian

Reputation: 213829

Please help

Run your program under Valgrind or Address Sanitizer (also implemented in GCC). Chances are, they'll point you straight at your bug.

Lot of things happen

It's likely that the bug happens there.

Upvotes: 0

Related Questions