tags:

views:

375

answers:

1

I have some C code that is something of a puzzle. For a reason to do with this code, I'm wondering how I can tell if a struct object is ending up on the heap or stack?

The objects are not being created with malloc or calloc. They start their life in the form of an array. For the purposes of this post, I'm going to call the struct Emp.

Emp myEmp[6];

/* Each myEmp[?] item is populated in code */

The objects are sorted and manipulated in various ways and at some point, the objects are copied and then handed to a array-pointer. The copy is done via memcpy. The objects are then put in to something like: Emp* emps_a[6].

The objects go from a copy and are assigned in to the above emps_a.

int i;
for( i = 0; i < n; i++ )
{
    emps_a[i] = myEmpsCopy + i;
}

I'm not sure if some or any of this has bearing on my question. I never need free() or do memory clean up... I'm afraid I don't know too much about C.

The help is greatly appreciated.

+9  A: 

Leaving global variables and variables declared with static modifier (which are allocated in a separate memory region) aside, local variables declared in a function body are allocated on the stack whereas whatever you call malloc for is allocated on the heap. Also, C99 variable sized arrays and memory allocated with _alloca will end up on stack.

int* x[10];   // The addresses are held on the stack
int i;        // On the stack
for(i = 0; i < 10; ++i)
   x[i] = malloc(sizeof(int)*10);  // Allocates memory on the heap

For example, in the above code, there's an array of int* values on the stack holding addresses to 10 different locations in the heap.

Mehrdad Afshari
...and "static" variables are probably in their own region of memory.
Alex Martelli
Yeah, along with globally declared things.
Mehrdad Afshari
So your saying in my example above, everything ends up on the stack. It isn't possible for anything to end up on the heap?
Frank V
C is very explicit. If you don't malloc() it, it's not on the heap.
John Kugelman
Indeed. In C, that's the whole thing. C++ might run constructors that can end up putting some stuff on heap too.
Mehrdad Afshari
"Whatever you're declaring statically in a function body is allocated on stack" -- garbage and needed editing before it deserved to be accepted. Whatever you're declaring NON-STATICALLY in a function body is allocated on stack...
Windows programmer
@Windows programmer: "statically declaring" doesn't mean declaring with the "static" modifier. I mean to say, the declaration is "static" at compile time, as opposed to "dynamic allocation."
Mehrdad Afshari
OK. The edited version of the answer looks fine too.
Windows programmer