Search code examples
cinitializationmemory-managementdynamic-memory-allocation

C function: is this dynamic allocation? initializating an array with a changing length


Suppose I have a C function:

void myFunction(..., int nObs){
    int myVec[nObs] ;
    ...
}

Is myVec being dynamically allocated? nObs is not constant whenever myFunction is called. I ask because I am currently programming with this habit, and a friend was having errors with his program where the culprit is he didn't dynamically allocate his arrays. I want to know whether my habit of programming (initializing like in the above example) is a safe habit.

Thanks.


Solution

  • To answer your question, it's not considered dynamic allocation because it's in the stack. Before this was allowed, you could on some platforms simulate the same variable length allocation on the stack with a function alloca, but that was not portable. This is (if you program for C99).