Solved

malloc() and fork()

Posted on 1998-07-16
2
542 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
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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

In this article, I'll describe -- and show pictures of -- some of the significant additions that have been made available to programmers in the MFC Feature Pack for Visual C++ 2008.  These same feature are in the MFC libraries that come with Visual …
Introduction: Hints for the grid button.  Nested classes, templated collections.  Squash that darned bug! Continuing from the sixth article about sudoku.   Open the project in visual studio. First we will finish with the SUD_SETVALUE messa…
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 video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

746 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now