3

I came across this example of C99 Variable-length arrays on Wikipedia:

float read_and_process(int n)
{
    float vals[n];

    for (int i = 0; i < n; i++)
        vals[i] = read_val();
    return process(vals, n);
}

Is this incorrect? I was under the impression that variable-length arrays are still just pointers which means the above code is passing the expired pointer vals to the process(...) function.

2
  • 3
    Arrays are not pointers. They just decay to pointers -- annoyingly easily, some would say. Commented Dec 29, 2011 at 5:47
  • +1 for "Arrays are not pointers". See also section 6 of the comp.lang.c FAQ Commented Dec 29, 2011 at 6:36

2 Answers 2

7

The pointer hasn't expired. It is a pointer to valid memory until the end of the function read_and_process. Which means it is still defined when process is called.

This would be an example of invalid usage:

float read_and_process(int n)
{
    float vals[n];

    for (int i = 0; i < n; i++)
        vals[i] = read_val();
    return vals;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Oh ok that makes sense. As long as you're growing the stack the memory address must still be valid.
@Jeff: A better way to look at it: the array (or any local non-static object) continues to exist until the function that created it returns. (Actually it's tied to the enclosing block, but it's the same in this case.) The lifetime of a local object is a span of time during execution, not a region of program text. Calling process doesn't terminate the execution of read_and_process, so the array still exists.
1

Don't forget that the stack frame that contains all of read_and_process()'s automatic variables, including float vals[n], is still valid and in memory when process() is executed.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.