Reputation: 4287
I use two ways to create array. I used to think they are the same but they seem different.
char *buffer=malloc((sizeof(char)*100));
char buffer1[100];
strcpy(buffer,"Eric");
strcpy(buffer1,"Eric");
for (int i=0; i<100; i++) {
printf("%c",buffer[i]);
}
printf("\n");
for (int i=0; i<100; i++) {
printf("%c",buffer1[i]);
}
the result is
Eric
Eric?!^?{"Gl?(?!^?(?!^?@?!^?0?P?!^?
And I inspected the array then I found there are some strange numbers in the array. But why when I created the array using malloc. The strange numbers didn't exist?
Upvotes: 0
Views: 81
Reputation: 41180
Apparently, malloc
on your system is clearing the returned memory. This may be done to prevent data from leaking from one process to another, or to help with debugging. Or you may have just gotten lucky, and next time malloc
won't clear the memory, e.g., because it came from a pool that is already local to your process. So, don't count on it. calloc
is available for this purpose.
The second mechanism just adjusts a stack pointer. Whatever was on the stack before the function was entered is still there. Clearing it would cost time, so C compilers do not generate code to do so.
Upvotes: 3