Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is an array initialized by an initializer list stored?

Tags:

c

memory

Given this piece of code:

(void)someFunction(void) {
    int array[] = {1,2,3,4,5,6,7,8,9,10};
}

Where are the values of the array stored?

  • Stack?
  • Heap?
  • Together with those string literals. (Is it called High Frequency Heap?)
  • Somewhere else?

I'm asking because I'm unsure regarding this question:

Create an array of integers property in objective-c

like image 616
Georg Schölly Avatar asked Jan 25 '09 00:01

Georg Schölly


2 Answers

The array itself will be on the stack. There will be a bit of code on entry to the function that copies the values which are stored in some unnamed array in a global/static memory area into the local array on the stack. It's likely that the unnamed global/static array with the initial values is in the same general memory area as string literals.

Note however, that none of this is required by the standard - but it's pretty much how any compiler will implement it. A smart enough compiler might notice that the values are simply incremented integer values and might gen up a loop to init the local array,

(this answer assumes C/C++ - I don't know if Objective-C would change any of this).

like image 52
Michael Burr Avatar answered Sep 17 '22 13:09

Michael Burr


As Micheal has said, where the values of the initializer list will be stored depends on the compiler and the optimization levels. For example, gcc without optimizations will just generate the code to move constants to the appropriate locations in the array, ie the actual values will only be stored in the code itself. You can easily check what will happen if you don't compile to object code, but let your compiler output assembler instead.

like image 23
Christoph Avatar answered Sep 20 '22 13:09

Christoph