memory leaks

Status
Not open for further replies.
I am writing a shell program for a UNIX system for a project in an OS design class. I am now at the stage where i can call fork() and exec(). But the following just come into mind.

Simply put, in C/C++. the main function is decleared
code:<HR>
Code:
 int main (int argc, char* argv[])
who is responsible for cleaning up the memory allocated for argv[]? the caller? (the shell) or the main function itself?

This has never occured to me before (or i just had crappy instructors that did not talk about these things)

more precisely, the following comes into mind...

When i call fork(), memory space of the caller is mirrored in the child process. and so is the argv[] that is prepared before calling exec(). Once I call, say, exec("huh.exe", argv[]), the memory of that child process is wiped and replaced with huh.exe. The parent process (assuming the shell program) of course has argv[] on hand, which it should probably free up. But how about the child process? where does the argv[] that i passed to it go? how am i gonna free that up?

Some of you is going tell me that UNIX's memory system is going to reclaim those memory once the process ends, which is fine, but is there a way to gracefully free them up? (probably not from the parent process, coz the child gets a duplicate from the parent)

The memory leak really bothers me because i need to make the assumption that the memory subsystem would take care of it...

I appologize for the long post. I am not really good at expressing myself. Thank you for any advice.

edit: spelling...
 

Midlands

Ars Praetorian
535
Subscriptor
LGM,

The OS takes care of it for you. :D

When you call exec(), Unix takes the arguments you pass it and copies them into a special area of memory in the process along with all the environment variables that are being handed along. The new binary image is then loaded from disk and handed a pointer to these strings as its argv (and 'envp', if you include that parameter on main()).

The old program can't possibly deallocate those strings, because it's obliterated the moment it calls exec(). The new program won't want to deallocate them, because it needs to look at them as its arguments.

So, you might say, "OK, but, still, once I'm done looking at them, I want to get back the memory they use". The answer is "Sorry, Charlie". They, like the environment, are not freeable -- and may not even be writable (that is, if you try to store to them, you may segfault). Consider them to be like the file handles you have to stdin/stdout/stderr, etc. -- even if you don't use them, you pay the cost, but the cost is so trivial, it doesn't matter.
 

wb

Ars Legatus Legionis
25,208
Subscriptor
Umm..Ok, i get the part after calling execv(), that i don't need to worry about the argv[] array that i passed into execv(), but how about the parent that called fork(), who also holds a copy of that argv[], should i clear it? (i guess, by saying "copy", i probably should...)

No. Don't delete, realloc, or free anything the OS passes into your program. The OS takes care of all this for you...please put your mind at rest. Anything that you call new or malloc() to allocate is yours to manage, however. Of course local variables in function and class scopes are also yours to manage to a point, but they will be taken care of for you by the compiler when they go out of scope. Global and static variables (basically what argc and argv are) will be cleaned up when the program terminates.
 
I guess I wasn't so clear on why I want to delete the argv[].

I am writing a commandline interpreter (class project) running on top of the existing shell. When I parse the incoming commandline, there will, naturally, be switches and so on for me to rearrange (basically malloc, strcpy, etc) onto an array that will eventually be passed onto the command that i need to execute (child process).

My confusion is this:

Since I did malloc() in the parent process before I fork() off, there are 2 copies of that argv[] and the strings that it contains; one belongs to the parent address space and the other to child (before execv()). I am pretty certain that I need to free() those that are in the parent process. But how about the child?

Of course it is nonsense to free() them before calling execv(), but from what I understand now, I basically need not worry about free()ing them at all. Once I call execv(), the OS will (kinda) make a copy of the argv[], put it some place safe (the stack?), and in the mean time, wipe everything out that I have allocated. Please correct me if I am wrong.

OT:
I know whatever is in the parent memory space is mirrored onto the child memory space once I call fork(), so are the chunks of memory that I acquired with malloc(). I know the *nix memory system is robust and all, but I am having a hard time convincing myself that those chunks of memory will be automagically be wiped out / reclaimed from the child process. I have always pride myself for writing clean, non-sloppy code, and this makes me feel uneasy :(

Thank you.
 

wb

Ars Legatus Legionis
25,208
Subscriptor
Since I did malloc() in the parent process before I fork() off, there are 2 copies of that argv[] and the strings that it contains; one belongs to the parent address space and the other to child (before execv()). I am pretty certain that I need to free() those that are in the parent process. But how about the child?

Ok, I think I understand what you are trying to say. First, to make things absolutely clear, I want to establish that you are not in fact malloc()'ing or free()'ing argv, but a copy of argv, correct?

I don't think you want to free the memory in both the parent and child processes, as this will result in bad things happening. The pointer to the memory you allocate in the parent process is still going to point to the same memory location in the child process. When you free it in one, you free it in the other. This also begs the question of whether you might need to perform some synchronization to keep from freeing the memory in one process while you are still using it in the other.
 

John S

Ars Scholae Palatinae
1,464
Subscriptor
LGM, when you fork(), the new process which is created will have it's own memory for static storage (though if I recall, most unices don't duplicate the text section since it isn't writable and will most likely be replaced by an exec() call anyway). Each element of the argument array you pass to execv is essentially strcpy'd to this new storage space. Think about using execl where the arguments might just be literal strings, no initial storage exists, but it still works cause those strings are copied to the new memory.

So, yes, go ahead and free() the memory you used to pass those arguments.
 

MrHat

Ars Scholae Palatinae
952
Are you sure about this? I was under the impression that fork duplicated *everything*, and completely isolated the processes from each other.

Nope, AFAIK that's dead wrong. The child gets a copy of the parent's entire address space, although the OS may not create a true copy of a page until it's written to.

Now if the two processes are sharing the address space via clone() or some similar mechanism, you're (er... the poster you quoted) pretty much correct.
 
hehe....with people saying different thing, it is getting more confusing by the post :D

OK, let's see if I get this right.

Suppose a parent process does this
code:<HR>
Code:
 STR = (char*) malloc (5);
strcpy (STR, "ABCD");
before fork(). Suppose the STR has a numerical value of 500, and that maps to a physcial address of 1000.
Let's say that is the only thing in the argv[] that is eventually passed to execv().

After fork(). the parent process's STR == 500, and maps to 1000. This much is clear.

According to wb, the child process's STR also equals to 500, and is mapping to the same address 1000 (which I think is probably wrong, unless). As the result, I must not free() STR from the parent process nor the child process.

On the other hand, according to euzeka and MrHat said that the STR of the child process maps to, say, 2000 (I now tend to agree with this).
So, right after fork(), I can safely free() STR in the parent process.

These are all before calling execv(). Now, according to Midlands and John S, as soon as I call execv() with argv[] passed to it, the system is gonna (sort of) strcpy() "ABCD" to some place that is under the OS's control. The chunk of memory that the child's STR points to (2000) is reclaimed as execv() wipe out the child process' space and replace it with the new program. Therefore, I need not worry about that chunk of memory (2000) (this kinda make sense now, because those memory is allocated indirectly by the fork() / OS, not by the parent process)

Sorry about restating the problem again and again, and I thank all those who patiently read through all these questions.
 

wb

Ars Legatus Legionis
25,208
Subscriptor
According to wb, the child process's STR also equals to 500, and is mapping to the same address 1000 (which I think is probably wrong, unless). As the result, I must not free() STR from the parent process nor the child process.

Doh! Somehow, I was thinking of multithreading instead of separate processes. The latter is correct (OS creates a copy of the parent process address space).
 

Midlands

Ars Praetorian
535
Subscriptor
LGM: Yes, I think the discussion sorted things out now.

The right way to think about it is this:

- You're allocating the argv[] array before there are two processes.
- Once you fork(), *both* processes have their *own* copies of this data -- so each will need to clean it up.
- The child process cleans it up by calling exec(); since exec() obliterates your entire address space, it's gone -- poof!
- The parent process will need to clean it up manually, using free().

Other things to note:

- The parent process never, ever actually executes a system call that takes this argv[] as a parameter -- so it's just memory you're allocating, using yourself, and thus must free yourself.
- fork() originally was implemented on Unix systems by doing an actual, full-scale copy of the entire process's address space -- and this is how its semantics are defined. So even if your Unix does magic with copy-on-write and virtualization translations (nearly all modern Unices do), you can just think of it as a full duplicate -- end of story.

The only way to really make things complicated is if you're spawning child threads or creating shared memory regions. Since you're not, what's going on is actually very simple. It's easy to make yourself think it's a lot more complex than it actually is.
 
Status
Not open for further replies.