Assume that I have the below statement in my code. I would like to ask where will memory be allocated, in heap or in stack? What is the difference between a heap and a stack? How can I free the allocated memory?
Code:char* x = "hello";
Assume that I have the below statement in my code. I would like to ask where will memory be allocated, in heap or in stack? What is the difference between a heap and a stack? How can I free the allocated memory?
Code:char* x = "hello";
The stack is the part of system memory where all the variables are stored before run-time. The heap is the part of system memory where all the variables are stored during run-time. This means that if you are declaring a variable "i" in your code and assigning the value of say "123" then that will be stored in your stack because the compiler knows the value during the compile time (step that is before run-time). Whereas if you define a pointer variable (as in your statement) but want to initialize it somewhere else then that will be stored in your heap, since it is unknown to compiler at the compile time.
If you perform certain tasks such as if you have a variable "area" and its value is to be computed by some expression then this variable will remain in stack. In short stack is used for storing local variables (variables declared inside a function), function parameters, etc. These variables do not have any proper value and usually stores garbage in them. The heap stores dynamically assigned variables (one declared with malloc). It stores any global variables used, static local variables etc.
Since you have directly declared the variable and assigned the value in your code, the variable "x" will be stored in your stack because the compiler already knows the variable value. You can free the memory using 2 ways, either using "delete" or if it is declared using "malloc" then use "free"Code:char* x = "hello";
Bookmarks