Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where machine instructions of a program stored during runtime?

So far as I know, whenever we run any program, the machine instructions of the program is loaded in RAM. Again, there are two regions of memory: stack and heap.

My question is: Which region of memory the machine instruction stored in? stack or heap?

I learnt that the following program gives a runtime error though there is no variable declared inside the function. The reason behind this is the overflow of stack. Then should I assume that the machines instructions of the function is stored in stack?

int func()
    {
            return func();
    }
like image 391
Muktadir Rahman Avatar asked Jan 29 '15 15:01

Muktadir Rahman


1 Answers

Neither, as it is not dynamically allocated the way stack and heap are.

The executable loader loads the executable (.text) and any static data it contains, like the initial values of global variables (.data / .rodata), into an unused RAM area. It then sets up any zero-initialized memory the executable asked for (.bss).

Only then is the stack set up for main(). Stack memory is allocated on the stack if you enter another function, holding the return address, function arguments, and any locally declared variables as well as any memory allocated via alloca().[1] Memory is released when you return from the function.

Heap memory is allocated by malloc(), calloc(), or realloc(). It gets released when you free() or realloc() it.

The RAM used for the executable and its static data does not get released until the process terminates.

Thus, stack and heap are, basically, under control of the application. The memory of the executable itself is under control of the executable loader / the operating system. In appropriately equipped operating systems, you don't even have write access to that memory.


Regarding your edited question, no. (Bad style, editing a question to give it a completely new angle.)

The executable code remains where it was loaded. Calling a function does not place machine instructions on the stack. The only thing your func() (a function taking no arguments) places on the stack is the return address, a pointer that indicates where execution should continue once the current function returns.

Since none of the calls ever returns, your program keeps adding return addresses on the stack, until that cannot hold any more. This has nothing to do with machine code instructions at all.


[1]: Note that none of this is actually part and parcel of the C language standard, but implementation-defined, and may differ -- I presented a simplified version of affairs. For example, function parameters might be passed in CPU registers instead of on the stack.

like image 143
DevSolar Avatar answered Sep 20 '22 10:09

DevSolar