Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an uninitialized variable occupy memory?

Tags:

c

In this short example, a question from an exam I had yesterday:

int main() {
    short a;
}

Does 'a' occupy any memory space? When I made:

printf("%u %d\n",a, sizeof(a));

I get printed a '0 2' so I thought the '0' meant no memory was yet initialized but my teacher says yes, it occupies 2 bytes already.

Thanks, Dani.

like image 520
daniel sp Avatar asked Mar 26 '26 22:03

daniel sp


2 Answers

The correct answer is 'maybe'. The compiler must give you the illusion that it does occupy memory, and in most practical cases it will.

However, the compiler is free to do what it wants as long as it maintains that illusion. In your example without the printf, the variable a is never used. The compiler is free to optimize it out, so it might not use any memory. Indeed that often happens when you enable optimization flags, such as -O3 for gcc.

like image 96
Adam Avatar answered Mar 28 '26 12:03

Adam


Does an initialized variable occupies memory?

Yes. I am guessing you meant to use uninitialized there. The answer is still Yes.

When you use the value of an uninitialized variable, like in the call to printf, the program is subject to undefined behavior.

However, sizeof(a) is computed at compile time. It does not depend on whether the variable is initialized or not.

like image 28
R Sahu Avatar answered Mar 28 '26 14:03

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!