C Array Instantiation - Stack or Heap Allocation?

前端 未结 2 1157
抹茶落季
抹茶落季 2020-12-08 15:33

I guarantee that this question has been asked before, but I haven\'t been able to find it via search; sorry in advance for any redundancies.

It\'s my (potentially wr

相关标签:
2条回答
  • 2020-12-08 16:00

    Similarly, is the 100% sole situation where you have to use free() when the data was allocated via malloc?

    Yes. (Apart from calloc and realloc, their return value is also to be free()'d. Similarly, there are functions that use malloc() and this fact is documented, for example strdup() - the return value of these functions is also to be freed using free(), obviously.)

    char anotherCharArray[someVariable + 50];
    

    Would this go on the stack as well?

    Yes, it does (in most implementations - of course, it's not always true that you assume, but on most of the platforms, it is). And yes this is valid code, but it is only standard in C99.

    0 讨论(0)
  • 2020-12-08 16:01

    If char charArray[50]; is defined at file scope (outside of all functions) or is static, it's not going to be on the stack, it's going to be a global preallocated at program's start variable. If it's not static and is defined at function scope, it's going to be on the stack.

    char anotherCharArray[someVariable + 50]; can only be defined at function scope and is going to be on the stack.

    All of the above applies to typical implementations of C. Atypical ones may use the heap instead of the stack and instead of the preallocated space in the data section of the program.

    You don't free() what hasn't been allocated with malloc(), calloc() or realloc(). Simple. Some functions may imply the use of one of the above, e.g. POSIX strdup().

    0 讨论(0)
提交回复
热议问题