Search code examples
cpointersmallocdynamic-memory-allocation

The difference between char string[100] and char *string = malloc(100)


If it does allocate memory why do you not have to free string?

like you would if you did:

char *string;
string = malloc(100);

Does it perhaps differ in some way because char[100] is static and the other way is dynamic?


Solution

  • char string[100]; allocates memory as long as the variable lives.

    If it is a static variable this is as long as the program runs. The variable is allocated statically in the bss or data segment (or rodata or any other segment the compiler-linker-system sees fit.)

    If it is a dynamic ("automatic" in the C standard) variable this is as long as the containing block runs. The variable is most commonly allocated on the stack and the space is automatically "freed" at the end of the block when the stack pointer is adjusted.

    In contrary, if you use malloc() the space is commonly allocated on the heap. You have to manage it yourself by giving it back through free() if you're done.

    So, to answer your question literally, no, char string[100]; does not allocate memory through malloc(). Therefore there is no need to call free() and it will be an error.