Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we store instructions in dynamically allocated memory in C language?

Tags:

c

heap-memory

Its well known that we can store DATA in dynamically allocated memory.

However, I was wondering if we can store NEW INSTRUCTIONS or NEW FUNCTIONS on the heap? Any real applications?

Preparing for interviews, so please bear with me if this isn't a sensible question.

like image 264
Aditya369 Avatar asked Nov 02 '11 06:11

Aditya369


People also ask

Is dynamic memory allocation possible in C?

The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib. h header file.


1 Answers

The question is about C language, so the answer should be no — there is nothing in the language alone that defines anything like storing a function on the heap.

However, if we add knowledge of implementation details and OS (relocation tables, page protection, etc), then yes, it's possible. For example, custom dynamic code loaders (that do not use OS-provided DLL/SO loading) work this way.

like image 174
hamstergene Avatar answered Nov 15 '22 05:11

hamstergene