Mosab Shaheen Mosab Shaheen - 6 months ago 30
C Question

Where in memory are variables stored in c, Heap or Stack?

int main(void)
{
int a=10;
char b[10]="HELLO";
const int x=10;
return 0;
}


"a" will be stored in the stack only (data segment not possible) with its value(10)

"b" will be stored as a pointer (because the array is a pointer to the first element) in the stack and "HELLO" will be stored in heap ( like if we are using malloc).

"x" can be stored in data, stack, or text depending on compiler.

Please correct me if I am wrong.

Answer Source

"a" will be stored in the stack only (data segment not possible) with its value(10)

Correct.

"b" will be stored as a pointer (because the array is a pointer to the first element) in the stack and "HELLO" will be stored in heap ( like if we are using malloc).

Incorrect.

Think of that line as:

char b[10];
strcpy(b, "HELLO");

b is an array, not a pointer. Stack memory is used for the array.

"x" can be stored in data, stack, or text depending on compiler.

Correct.