spatara spatara - 1 month ago 7
C Question

Why am I getting this memory access error 'double free or corruption'?

I am getting the following type of error. I know it has something to do with me improperly accessing memory, but I don't exactly how. Please help me see where I have gone wrong.

*note I have simplified my function and it is not obvious what the variables are doing, I just need to know how I am implementing the function incorrectly or where I am misusing memory access.

int my_function(char const *file_name, size_t max)
{

myStruct.pStore = fopen(file_name,"w+"); //pStore is a FILE*
myStruct.max = max;

// fill the with zeros ('0')
int numberOfZeros = max*SIZE;
char zeros[numberOfZeros];

int i=0;
while(i<numberOfZeros) // insert zero's
{
zeros[i]='0';
i++;
}
fwrite(zeros,sizeof(char),numberOfZeros,myStruct.pStore);
fclose(myStruct.pStore);

return EXIT_SUCCESS;


The error I am given:

*** glibc detected *** /home/.../: double free or corruption (top): 0x0804c008 ***
======= Backtrace: =========
/lib/i386-linux-gnu/libc.so.6(+0x73e42)[0xb7e82e42]
/lib/i386-linux-gnu/libc.so.6(fclose+0x154)[0xb7e72384]
/home/2012/spatar/cs/specs/release[0x80486b0]
/home/2012/spatar/cs/specs/release[0x8048acd]
/home/2012/spatar/cs/specs/release[0x8048af0]
/lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xf3)[0xb7e284d3]
/home/2012/spatar/cs/specs/release[0x80484e1]
======= Memory map: ========
08048000-0804a000 r-xp 00000000 00:3b 2331829 /home/2012/spatar/cs/Aspecs/release
0804a000-0804b000 r--p 00001000 00:3b 2331829 /home/2012/spatar/cs/specs/release
0804b000-0804c000 rw-p 00002000 00:3b 2331829 /home/2012/spatar/cs/specs/release
0804c000-0806d000 rw-p 00000000 00:00 0 [heap]
b7e0e000-b7e0f000 rw-p 00000000 00:00 0
b7e0f000-b7fae000 r-xp 00000000 00:11 5415 /lib/i386-linux-gnu/libc-2.15.so
b7fae000-b7fb0000 r--p 0019f000 00:11 5415 /lib/i386-linux-gnu/libc-2.15.so
b7fb0000-b7fb1000 rw-p 001a1000 00:11 5415 /lib/i386-linux-gnu/libc-2.15.so
b7fb1000-b7fb4000 rw-p 00000000 00:00 0
b7fbc000-b7fd8000 r-xp 00000000 00:11 5426 /lib/i386-linux-gnu/libgcc_s.so.1
b7fd8000-b7fd9000 r--p 0001b000 00:11 5426 /lib/i386-linux-gnu/libgcc_s.so.1
b7fd9000-b7fda000 rw-p 0001c000 00:11 5426 /lib/i386-linux-gnu/libgcc_s.so.1
b7fda000-b7fdd000 rw-p 00000000 00:00 0
b7fdd000-b7fde000 r-xp 00000000 00:00 0 [vdso]
b7fde000-b7ffe000 r-xp 00000000 00:11 5405 /lib/i386-linux-gnu/ld-2.15.so
b7ffe000-b7fff000 r--p 0001f000 00:11 5405 /lib/i386-linux-gnu/ld-2.15.so
b7fff000-b8000000 rw-p 00020000 00:11 5405 /lib/i386-linux-gnu/ld-2.15.so
bffdf000-c0000000 rw-p 00000000 00:00 0 [stack]

Answer Source

It looks like you are trying to free memory that has already been freed or was dereferenced.

Link your program with efence or run it with valgrind.

This will tell you where your pointer gets dereferenced.