First off I am pretty new to C, so I probably just have a fundamental misunderstanding here. Given code such as this:
int main()
{
char ack[100];
char *bar;
bar = malloc(100);
strncpy(ack, "testing", 7);
bar = "testing";
return 0;
}
ack when examined by gdb looks like this:
(gdb) p ack
$1 = "testing\000\360WV\000\000\000\000\000\277\000\000\000\000\000\000
'\000'\000\220\005@",<repeats 13 times>, "\003\004@", '\000' <repeats 13 times>
"\325,\005@\000\000\000\000\000H\214\246\367\377\177\000\000\220\005@",
'\000' <repeats 13 times>, "P\004@\000\000\000\000\000\360\342\377\377"`
This makes sense to me given how I initialized ack. What I don’t quite get is why bar looks like this:
(gdb) p bar
$2 = 0x40066c "testing"
I allocated the same amount of storage (as far as I know) as I did when I requested space for ack but malloc doesn’t have the extra junk. As I understand it, malloc doesn’t do any sort of data initialization or anything, so I’m a bit confused. The reason that this came up is an issue I was having with strstr. Basically, when I would read in data from a file (fgets), to a char array with a specific size strstr() would fail (which I was assuming was because of the extra junk). Working with a pointer and malloc’d memory worked just fine. Anyway, I have a few specific questions.
-
Is the behavior of this malloc’d variable expected? Is there some optimization going on here (I compiled with gcc, but didn’t do any optimizations) or is gdb not showing me everything? Should there be “junk” associated with that variable?
-
Am I even using malloc correctly? Should I be initializing all of the memory I requested? If so, how?
Thank you!
EDIT
Thanks to everyone who responded! I’ve learned quite a few things from you all and it’s much appreciated. I now see the problem with the code I posted above, and the original issue that I was having with fgets() and strstr().
re-assigns the pointer
barto point to a static buffer holding the string"testing", i.e. it no longer points to yourmalloc‘d array. This is a memory leak.To get a string into the
malloc‘d buffer, usestrcpy,strncpyormemcpy, like you did withack.