Solved

malloc() and fork()

Posted on 1998-07-16
2
549 Views
Last Modified: 2013-12-26
When I call fork(), are all my dynamic memory pointers copied, and pointing to new memory addresses? Is this chunk of code correct? Please explain. Thank You.

int fork_func(void)
{
   char *p;

   p = (char *)malloc(100);
   if (!fork()) {
      /** some processing **/
      free((void *)p);
   }
   free((void *)p);
   return 0;
}
0
Comment
Question by:Ignatz
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 32

Accepted Solution

by:
jhance earned 50 total points
ID: 1294939
You are correct, fork() duplicates the current variables and stack.  The problem with the above code is that free() will get called twice for the child.  You should do this instead:

int fork_func(void)
{
   char *p;

   p = (char *)malloc(100);
   switch(fork()){
   case 0: // child
      /** some processing **/
      free((void *)p);
      return 0;

   case -1: // error
      // some error processing
     free((void *)p);
     return 1;

   default:  // normal parent process
   free((void *)p);
  }
   return 0;
}
0
 

Author Comment

by:Ignatz
ID: 1294940
Thanks, I am currently calling exit(0) after free() in child process, but I forgot to put that in my sample code.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Here is how to use MFC's automatic Radio Button handling in your dialog boxes and forms.  Beginner programmers usually start with a OnClick handler for each radio button and that's just not the right way to go.  MFC has a very cool system for handli…
Introduction: Displaying information on the statusbar.   Continuing from the third article about sudoku.   Open the project in visual studio. Status bar – let’s display the timestamp there.  We need to get the timestamp from the document s…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.

717 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question