Hi...
Been working on some project and ran into trouble with dynamic memory allocation... I wrote a short sample code to understand the matter, but I really can't get it to work... So I need help...
Here's the code:
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char **pointers;
int i, strings = 2;
pointers = malloc(strings++ * sizeof(char));
for (i = 0; i < 5; i++)
{
pointers[i] = malloc(256 * sizeof(char));
scanf("%s", pointers[i]);
pointers = realloc(pointers, strings++ * sizeof(char));
}
printf("\n--------------\n");
for (i = 0; i < 5; i++)
printf("%s\n", pointers[i]);
return 0;
}
When I'm trying to run the compiled program, after inputting all 5 strings I get the following message:
Code:
*** glibc detected *** ./realloc: realloc(): invalid next size: 0x0804a008 ***
======= Backtrace: =========
/lib/libc.so.6[0xb7ee4105]
/lib/libc.so.6[0xb7ee7d19]
/lib/libc.so.6(realloc+0x106)[0xb7ee8a66]
./realloc[0x80484a6]
/lib/libc.so.6(__libc_start_main+0xe5)[0xb7e8b6a5]
./realloc[0x8048391]
======= Memory map: ========
08048000-08049000 r-xp 00000000 03:01 335765 /home/dark/code/realloc
08049000-0804a000 rw-p 00000000 03:01 335765 /home/dark/code/realloc
0804a000-0806b000 rw-p 0804a000 00:00 0 [heap]
b7d00000-b7d21000 rw-p b7d00000 00:00 0
b7d21000-b7e00000 ---p b7d21000 00:00 0
b7e74000-b7e75000 rw-p b7e74000 00:00 0
b7e75000-b7fcf000 r-xp 00000000 03:01 14788 /lib/libc-2.9.so
b7fcf000-b7fd1000 r--p 0015a000 03:01 14788 /lib/libc-2.9.so
b7fd1000-b7fd2000 rw-p 0015c000 03:01 14788 /lib/libc-2.9.so
b7fd2000-b7fd6000 rw-p b7fd2000 00:00 0
b7fea000-b7ff6000 r-xp 00000000 03:01 206 /usr/lib/libgcc_s.so.1
b7ff6000-b7ff7000 rw-p 0000b000 03:01 206 /usr/lib/libgcc_s.so.1
b7ff7000-b7ff8000 rw-p b7ff7000 00:00 0
b7ff8000-b8016000 r-xp 00000000 03:01 14830 /lib/ld-2.9.so
b8016000-b8017000 r--p 0001e000 03:01 14830 /lib/ld-2.9.so
b8017000-b8018000 rw-p 0001f000 03:01 14830 /lib/ld-2.9.so
bfa02000-bfa17000 rw-p bffeb000 00:00 0 [stack]
ffffe000-fffff000 r-xp 00000000 00:00 0 [vdso]
Aborted
So... what's wrong?