4

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!

Community
  • 1
  • 1
musicmatze
  • 4,124
  • 7
  • 33
  • 48

3 Answers3

7
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

simonc
  • 41,632
  • 12
  • 85
  • 103
  • 1
    +1 but I'd go further than "there is no need". Casting the return value of malloc can hide certain subtle errors which would otherwise be flagged, especially in situations where pointers an ints are not the same width. – paxdiablo Dec 14 '12 at 12:06
  • 1
    @paxdiablo Good point. I've (hopefully) improved the wording in that part of my answer. – simonc Dec 14 '12 at 12:07
2

The first is allocated on the stack, and will be free'd when the variable goes out of scope. The second on the heap, and must be free()'d explicitly.

Both can be passed as pointers.

JasonD
  • 16,464
  • 2
  • 29
  • 44
2

In the first case, you allocate 80 characters on the stack, in the second case you allocate memory on the heap.

Both can be used as pointers, and passed around to functions, and both can be used with array indexing syntax as well.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621