I'm writing a simple shell as an OS course assignment, I need to search in the PATH to find the program user typed in, once I find the right directory, I malloc a piece of memory just enough to hold the directory name plus the program name, and I pass it as the first argument to execv().
I could have statically allocated 100 characters or so, but having a limit makes me feel uncomfortable. So when execv() executes, is the heap cleaned up or is that piece of memory lost?
It's maybe not a lot of memory but I'm just curious.
Dynamic memory allocation is the process of assigning the memory space during the execution time or the run time. Reasons and Advantage of allocating memory dynamically: When we do not know how much amount of memory would be needed for the program beforehand.
2) Dynamic memory allocation -- memory allocated during run time. Exact sizes or amounts (like the size of an array, for example) does not have to be known by the compiler in advance. This memory is allocated by the run time system.
C malloc() methodThe “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.
A dynamic variable can be a single variable or an array of values, each one is kept track of using a pointer. After a dynamic variable is no longer needed it is important to deallocate the memory, return its control to the operating system, by calling "delete" on the pointer.
When you exec()
, the entire process is (a) ended, so all resources including dynamic memory and some fd's as below, are reclaimed by the operating system, and (b) replaced: code, data, threads, ...
Re file descriptors, from "man execve"
:
File descriptors open in the calling process image remain open in the new process image, except for those for which the close-on-exec flag is set (see close(2) and fcntl(2)). Descriptors that remain open are unaffected by execve().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With