Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to dynamic allocated memory when calling execv()?

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.

like image 909
sxu Avatar asked Sep 12 '10 01:09

sxu


People also ask

What happens to dynamically allocated memory?

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.

Is dynamic memory is allocated during runtime?

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.

Does malloc allocate memory dynamically?

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.

Why do we need to call delete for dynamically allocated variables?

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.


1 Answers

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().

like image 117
user207421 Avatar answered Sep 22 '22 15:09

user207421