Possible Duplicate:
Difference between declaration and malloc
Is there a difference between these two programs?
int main(void) {
char str[80];
}
and
int main(void) {
char * str = (char*) malloc( sizeof(char) * 80 );
}
So is there a difference between using malloc
and the array-like syntax? So if I need memory for 80 characters, I should use malloc
and not the other possibility, right?
I'll try to answer my own question!
char str[80];
allocates 80 bytes on the stack. This will be automatically reclaimed when str
goes out of scope.
char * str = (char*) malloc( sizeof(char) * 80 );
allocates 80 bytes on the heap. This memory is available until you call free
.
Note that the second case can be simplified to
char * str = malloc(80);
i.e. You should not cast the return from malloc
in C and sizeof(char)
is guaranteed to be 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With