illnr
illnr

Reputation: 800

From where do the initial values of the variable length array (VLA) in [c] come?

example c code:

#include <stdio.h>
int main (int argc, char** args) {

    int k = 8;
    int sendbuffer[k]; // VLA

    for (int n = 0; n < k; n++) {
        printf("sendbuffer[%i]: %i \n", n, sendbuffer[n]);
    }

    return 0;
}

example output:

sendbuffer[0]: 1 
sendbuffer[1]: 0 
sendbuffer[2]: 1583871280 
sendbuffer[3]: 32767 
sendbuffer[4]: 22544384 
sendbuffer[5]: 1 
sendbuffer[6]: 1713234504 
sendbuffer[7]: 32767 

From where do the numbers in sendbuffer[] come from? And why are sendbuffer[2,4,6] the only ones that change when running the code again?

I'm using clang compiler on OSX El Capitan (compiling with gcc example.c)
Apple LLVM version 7.3.0 (clang-703.0.31)
Target: x86_64-apple-darwin15.4.0
Thread model: posix

If is a different behavior with other compiler/OS, I'd like to hear about these cases too.

Upvotes: 0

Views: 275

Answers (3)

John Bode
John Bode

Reputation: 123548

Online C 2011 standard, 6.7.9/10: "If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate..."

Unless you declare it at file scope or with the static keyword1, a variable won't be initialized to any specific value; the contents will be whatever was last written to that memory location.


  1. Neither of which apply to VLAs; they cannot be declared static or at file scope, nor can they have an explicit initializer.

Upvotes: 3

lost_in_the_source
lost_in_the_source

Reputation: 11237

This isn't just for VLAs; the behavior above is for any variable declaration. If you declare a variable, for example

int a;

This allocates sizeof(int) bytes on the stack, at whichever address the system chooses. The memory there is uninitalized; it is whatever happens to be there at the time. It is up to the programmer to initialize the memory.

Upvotes: 3

ForceBru
ForceBru

Reputation: 44878

These values are called garbage values, they're whatever that was in memory when the array was created interpreted as ints.

Your program just says to the OS: "gimme that part of memory pls" and so the OS does, giving it to your program without changing the contents.

Upvotes: 1

Related Questions