D
David Liang
I'm trying to write a string concatenator that (re)allocates memory,
but I'm getting a glibc error on free().
---
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *stracat(char *t, const char *s)
{
if (t == NULL)
if ((t = (char *) malloc(strlen(s)+1)) != NULL)
*t = '\0';
else
t = (char *) realloc(t, strlen(t)+strlen(s)+1);
if (t != NULL)
strcat(t, s);
return t;
}
int main(void)
{
char *p;
p = NULL;
p = stracat(p, "123456789");
p = stracat(p, "ABCDEF");
printf("%s\n", p);
free(p);
exit(0);
}
---
The output with the error:
123456789ABCDEF
*** glibc detected *** a.out: free(): invalid next size (fast):
0x0804a008 ***
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6[0xb7e01a85]
/lib/tls/i686/cmov/libc.so.6(cfree+0x90)[0xb7e054f0]
a.out[0x8048583]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe0)[0xb7dac450]
a.out[0x8048441]
======= Memory map: ========
....
The error disappears if the second call to stracat has fewer
characters, or if stracat was implemented in the following way, so I'm
assuming the problem is with the way I'm using realloc().
char *p = (char *) malloc((t == NULL ? 0 : strlen(t)) + strlen(s)
+ 1);
if (p != NULL)
{
strcpy(p, (t == NULL ? "" : t));
strcat(p, s);
}
free(t);
return p;
I'm using Ubuntu 8.04 with glibc 2.7. Any ideas on how to correct it
would be great, thanks.
but I'm getting a glibc error on free().
---
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *stracat(char *t, const char *s)
{
if (t == NULL)
if ((t = (char *) malloc(strlen(s)+1)) != NULL)
*t = '\0';
else
t = (char *) realloc(t, strlen(t)+strlen(s)+1);
if (t != NULL)
strcat(t, s);
return t;
}
int main(void)
{
char *p;
p = NULL;
p = stracat(p, "123456789");
p = stracat(p, "ABCDEF");
printf("%s\n", p);
free(p);
exit(0);
}
---
The output with the error:
123456789ABCDEF
*** glibc detected *** a.out: free(): invalid next size (fast):
0x0804a008 ***
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6[0xb7e01a85]
/lib/tls/i686/cmov/libc.so.6(cfree+0x90)[0xb7e054f0]
a.out[0x8048583]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe0)[0xb7dac450]
a.out[0x8048441]
======= Memory map: ========
....
The error disappears if the second call to stracat has fewer
characters, or if stracat was implemented in the following way, so I'm
assuming the problem is with the way I'm using realloc().
char *p = (char *) malloc((t == NULL ? 0 : strlen(t)) + strlen(s)
+ 1);
if (p != NULL)
{
strcpy(p, (t == NULL ? "" : t));
strcat(p, s);
}
free(t);
return p;
I'm using Ubuntu 8.04 with glibc 2.7. Any ideas on how to correct it
would be great, thanks.