?
Solved

malloc() and fork()

Posted on 1998-07-16
2
Medium Priority
?
550 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 200 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

Get proactive database performance tuning online

At Percona’s web store you can order full Percona Database Performance Audit in minutes. Find out the health of your database, and how to improve it. Pay online with a credit card. Improve your database performance now!

Question has a verified solution.

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

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…
Ready to get certified? Check out some courses that help you prepare for third-party exams.
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.
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

762 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