Solved

malloc() and fork()

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

Secure Your Active Directory - April 20, 2017

Active Directory plays a critical role in your company’s IT infrastructure and keeping it secure in today’s hacker-infested world is a must.
Microsoft published 300+ pages of guidance, but who has the time, money, and resources to implement? Register now to find an easier way.

Question has a verified solution.

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

Suggested Solutions

Introduction: Dialogs (1) modal - maintaining the database. Continuing from the ninth article about sudoku.   You might have heard of modal and modeless dialogs.  Here with this Sudoku application will we use one of each type: a modal dialog …
Introduction: Dialogs (2) modeless dialog and a worker thread.  Handling data shared between threads.  Recursive functions. Continuing from the tenth article about sudoku.   Last article we worked with a modal dialog to help maintain informat…
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.

696 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