EternalStudent EternalStudent - 2 months ago 6
C Question

What's the difference between a global variable and a dynmically allocatedv variable in C?

Assuming you know the value of the variable/pointer at compile time is there any difference between this:

int x = 5;

main(){
...
}


and this:

main(){

int *x = (int *) malloc(sizeof(int));
*x = 5;
...
}


I know the latter assigns memory to the heap and the former the stack, but a global variable will be stored through out the duration of the program as will things stored in the heap. So is there a functional difference between these two snippets of code?

Answer

Note: In all remarks below, I'm assuming that the code is compiled for and running on a normal everyday commonplace modern desktop computer.

I know the latter assigns memory to the heap

True, malloc obtains memory from a region of memory known as the heap.

and the former the stack

False, global variables are not stored on the stack. Initialized global variables have their values stored in the executable. The value is loaded from the executable into the data segment.

but a global variable will be stored through out the duration of the program

True.

as will things stored in the heap

False, memory obtained from malloc can be released with free. Therefore, items stored in the heap may be temporary. They are not necessarily "stored through out the duration of the program"

From the comments:

The similarity is that you'd have a variable storing 5 available globally through out the program.

False, the global variable in the first snippet is available throughout the program. The pointer in the second snippet is local to main and is only available to other functions if the pointer is passed as a parameter to those functions. For example, the following won't work (because foo has no access to x).

void foo( void ) {
    printf( "%d\n", *x );
}

int main( void ) {
    int *x = malloc(sizeof(int));
    *x = 5; 
}