doughyi8u |
12-17-2012 09:18 PM |
c free function returning unexpected output
I'm trying to learn about c pointers and used malloc to allocate memory for a pointer. I called malloc and then passed the pointer to a function (my_copy()). I've read that anything made w/ memory management functions should be freed after use. The problem is I get unexpected output from the free function. Here's the code in question:
Code:
#include <stdio.h>
#include <stdlib.h>
char *my_strcpy(char *, const char *);
int
main()
{
char *strA = "This is a string";
char *strB;
strB = malloc(sizeof(strA));
my_strcpy(strB, strA);
puts(strB);
free(strB);
return 0;
}
char *my_strcpy(char *destination, const char *source)
{
char *p;
p = destination;
while (*source != '\0')
{
*p++ = *source++;
}
*p = '\0';
return destination;
}
Here's the output when running the program:
Code:
bash-4.1$ ./test
This is a string
*** glibc detected *** ./test: free(): invalid next size (fast): 0x0804a008 ***
======= Backtrace: =========
/lib/libc.so.6(+0x714ae)[0xb76954ae]
/lib/libc.so.6(cfree+0x70)[0xb7699050]
./test[0x8048436]
/lib/libc.so.6(__libc_start_main+0xe6)[0xb763adb6]
./test[0x8048351]
======= Memory map: ========
08048000-08049000 r-xp 00000000 08:01 1334016 /home/doughy/work/sourcery/c/testing/test
08049000-0804a000 rw-p 00000000 08:01 1334016 /home/doughy/work/sourcery/c/testing/test
0804a000-0806b000 rw-p 00000000 00:00 0 [heap]
b74bf000-b74da000 r-xp 00000000 08:01 523382 /usr/lib/libgcc_s.so.1
b74da000-b74db000 rw-p 0001a000 08:01 523382 /usr/lib/libgcc_s.so.1
b7500000-b7521000 rw-p 00000000 00:00 0
b7521000-b7600000 ---p 00000000 00:00 0
b7623000-b7624000 rw-p 00000000 00:00 0
b7624000-b7780000 r-xp 00000000 08:01 654205 /lib/libc-2.13.so
b7780000-b7781000 ---p 0015c000 08:01 654205 /lib/libc-2.13.so
b7781000-b7783000 r--p 0015c000 08:01 654205 /lib/libc-2.13.so
b7783000-b7784000 rw-p 0015e000 08:01 654205 /lib/libc-2.13.so
b7784000-b7787000 rw-p 00000000 00:00 0
b77ab000-b77ad000 rw-p 00000000 00:00 0
b77ad000-b77ca000 r-xp 00000000 08:01 654247 /lib/ld-2.13.so
b77ca000-b77cb000 r--p 0001c000 08:01 654247 /lib/ld-2.13.so
b77cb000-b77cc000 rw-p 0001d000 08:01 654247 /lib/ld-2.13.so
bfd47000-bfd68000 rw-p 00000000 00:00 0 [stack]
ffffe000-fffff000 r-xp 00000000 00:00 0 [vdso]
Aborted
Can anyone tell me what is wrong?
|