Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between allocation [duplicate]

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!

like image 529
musicmatze Avatar asked Dec 20 '22 12:12

musicmatze


1 Answers

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

like image 180
simonc Avatar answered Dec 24 '22 02:12

simonc