Where is the memory allocated when I create this array? (C)

徘徊边缘 提交于 2019-12-23 10:57:41

问题


Let's say I do something like:

char* test[] = {"foo","bar","car"};

What exactly is this equivalent to if I did it the long way? Is this automatically creating memory that I will need to free? I'm just sort of confused. Thanks.


回答1:


test is an array of pointers to char located on the stack, and the string literals "foo","bar","car" are stored in a read only location. You need to free nothing.

test[0], test[1], test[2] point to read-only data. Please read about scoping rules and variable's lifetime in C. By default a variable which does not have storage-class specifier within a block has auto storage-class specifier which means a variable with a local lifetime.

{
    char* test[] = {"foo","bar","car"};
}
//cannot access test here 
test [0] = "new"; // Compile time error - ‘test’ undeclared

While trying to modify "bar" to "tar" will give runtime error:

char* test[] = {"foo","bar","car"};
test[1][0] = "tar"; // Run-time error

However this is fine test[0] starts to point to "new" from "foo":

test [0] ="new";

The reference to "foo" is lost.




回答2:


You are declaring an array of pointers. The pointers point to string literals.

The variable test follows the normal rule, if it's an automatic variable(scope inside some function), when out of the function, it gets out of scope, so you don't have to free the memory. If it's statically allocated(global or static variable), it has a life as long as the program, so you don't have to free the memory either.

The string literals that the pointers point have static storage, so you don't free them either.




回答3:


Test is an array of charecter pointers.When an initialization of values is provided for an array, C allows the possibility of leaving the square brackets empty [ ]. In this case, the compiler will assume a size for the array that matches the number of values included between braces { } .There is no need to free.




回答4:


The long way is to use malloc, and malloc the size of a string.

test will be pushed onto the heap

http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html



来源:https://stackoverflow.com/questions/19086769/where-is-the-memory-allocated-when-i-create-this-array-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!