First off, I'm pretty new to C, so I probably have a fundamental misunderstanding. This code, for example:
int main() { char ack[100]; char *bar; bar = malloc(100); strncpy(ack, "testing", 7); bar = "testing"; return 0; }
ack when checking 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"`
It makes sense to me how I initialized ack . I did not quite understand why bar looks like this:
(gdb) p bar $2 = 0x40066c "testing"
I allocated the same amount of memory (as far as I know) as I did when I requested a space for ack , but malloc has no extra garbage. As far as I understand, malloc does not perform any data initialization or anything else, so I'm a bit confused. The reason this happened is the problem that I ran into strstr. Basically, when I read data from a file (fgets), into a char array with a specific strstr () size, you didn’t work (which I assumed due to extra garbage). Working with malloc'd pointer and memory worked fine. Anyway, I have a few specific questions.
Is the behavior of this malloc'd variable expected? Is there some kind of optimization here (I compiled gcc but didn't do any optimizations), or does gdb not show me everything? Should there be "garbage" associated with this variable?
Am I using malloc correctly? Should I initialize all the memory I requested? If so, how?
Thanks!
EDIT
Thanks to all who responded! I learned a lot of things from all of you, and it was very much appreciated. Now I see a problem with the above code and the original problem that I came across with fgets () and strstr ().
user1156568
source share