Search code examples
c++cmemoryallocation

Dynamically created string allocated on heap or stack - C


Context

I was experimenting with getting C strings in C++ without allocating memory on the heap and came across this in testing:

#include <stddef.h>
#include <stdlib.h>

char* get_empty_c_string(size_t length) {
    char buffer[length];
    char *string = buffer;

    for (size_t i = 0; i ^ length; i++) *(string + i) = '\0';

    return string;
}

int main(void) {
    char *string = get_empty_c_string(20u); // Allocated on heap?
                                            // or stack?
    return 0;
}

Question

Is the C string returned allocated on heap or stack?

As far as I know:

  • Heap allocation occurs with the calloc, malloc & realloc C standard functions or new & new[] C++ keywords.

  • Stack allocation in most other cases.


Solution

  • The array buffer is a variable length array (VLA), meaning its size is determined at runtime. As a variable local to a function is resides on the stack. The pointer string then points to that array, and that pointer is returned. And because the returned pointer points to a local stack variable which goes out of scope, attempting to use that pointer will invoke undefined behavior.

    Also, note that VLAs are a C only feature.