Hello everybody!
I have a problem with realloc() which I cannot understand even after having searched for solutions in the forum and with google...
I have this simple program:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
printf("Insert a tel number (e.g: (555) 555-5555): ");
char buffer[51];
fgets(buffer,49,stdin);
char *pref, *startnum, *endnum;
pref=(char *)malloc(4*sizeof(char));
startnum=(char *)malloc(4*sizeof(char));
endnum=(char *)malloc(4*sizeof(char));
if (pref==NULL||startnum==NULL||endnum==NULL)
{
printf("Not enough memory! Ending...\n");
exit(1);
}
pref=strtok (buffer,"()");
startnum=strtok (NULL,"- ");
endnum=strtok (NULL,"\n");
printf("%s %s %s\n",pref,startnum,endnum);
char *tmp;
tmp=realloc(startnum,8*sizeof(char));
if (tmp==NULL)
{
printf("Not enough memory when reallocating memory! Ending...\n");
exit(1);
}
startnum=tmp;
strcat(startnum,endnum);
printf("%s %s\n",pref,startnum);
return 0;
}
and i get this output:
Code:
Insert a tel number (e.g: (555) 555-5555): (555) 555-5555
555 555 5555
*** glibc detected *** ./e8_14: realloc(): invalid pointer: 0xbfc719e3 ***
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6(realloc+0x39c)[0xb7ec49ec]
/lib/tls/i686/cmov/libc.so.6(realloc+0x3c)[0xb7ec468c]
./e8_14[0x8048677]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe0)[0xb7e6b450]
./e8_14[0x8048501]
======= Memory map: ========
08048000-08049000 r-xp 00000000 08:02 3408516 /home/federico/università/programmazione C/esercizi/e8_14
08049000-0804a000 rw-p 00000000 08:02 3408516 /home/federico/università/programmazione C/esercizi/e8_14
0804a000-0806b000 rw-p 0804a000 00:00 0 [heap]
b7e54000-b7e55000 rw-p b7e54000 00:00 0
b7e55000-b7f9e000 r-xp 00000000 08:02 1048704 /lib/tls/i686/cmov/libc-2.7.so
b7f9e000-b7f9f000 r--p 00149000 08:02 1048704 /lib/tls/i686/cmov/libc-2.7.so
b7f9f000-b7fa1000 rw-p 0014a000 08:02 1048704 /lib/tls/i686/cmov/libc-2.7.so
b7fa1000-b7fa4000 rw-p b7fa1000 00:00 0
b7fa6000-b7fb0000 r-xp 00000000 08:02 1015876 /lib/libgcc_s.so.1
b7fb0000-b7fb1000 rw-p 0000a000 08:02 1015876 /lib/libgcc_s.so.1
b7fb1000-b7fb5000 rw-p b7fb1000 00:00 0
b7fb5000-b7fb6000 r-xp b7fb5000 00:00 0 [vdso]
b7fb6000-b7fd0000 r-xp 00000000 08:02 1016004 /lib/ld-2.7.so
b7fd0000-b7fd2000 rw-p 00019000 08:02 1016004 /lib/ld-2.7.so
bfc5e000-bfc73000 rw-p bffeb000 00:00 0 [stack]
Aborted
can you please explain me the origin of the issue? Thanks a lot for your help! Bye!