Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

memory management - C Array Instantiation - Stack or Heap Allocation?

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 wrong) understanding that you only allocate to the stack when you know the size of an object at compile time. So in the case of initializing an array, you could do one of these (and this should go on the stack):

char charArray[50];

Since the size of this array is known at compile time, this should have no issues.

On the other hand, this (I believe) is also valid code:

char anotherCharArray[someVariable + 50];

Would this go on the stack as well? I am pretty sure the code segfaults if you free() this, so it makes me think it does, but it doesn't really make sense to me. Similarly, is the 100% sole situation where you have to use free() when the data was allocated via malloc?

Thanks in advance for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...