Find the answer to your Linux question:
Results 1 to 4 of 4
I am in the development of a multiple threaded app (POSIX threads). As usual, I have mallocs and free calls to get and free memory. When I run the app ...
  1. #1
    Just Joined!
    Join Date
    Dec 2008
    Posts
    2

    malloc fails in multiple pthreads

    I am in the development of a multiple threaded app (POSIX threads). As usual, I have mallocs and free calls to get and free memory. When I run the app with multiple threads, I hit upon malloc failed case (no more mem available) but with single thread, it is fine. I want to know whether there is any extra care that needs to be taken to ensure memory is freed in multiple threaded env ?

  2. #2
    Linux Engineer wje_lf's Avatar
    Join Date
    Sep 2007
    Location
    Mariposa
    Posts
    1,192
    I want to know whether there is any extra care that needs to be taken to ensure memory is freed in multiple threaded env
    No, no extra care is needed. You should free memory that you no longer need. This is true whether or not you use threads.

    You are getting a NULL pointer as the result of a malloc(), yes? In that case, do all your malloc()s like this:
    Code:
    block_size=(however you calculate the block size);
    pointer1=malloc(block_size);
    if(pointer1==NULL)
    {
      fprintf(stderr,"failure to malloc(%d)\n",block_size);
      exit(1);
    }
    The reason to do it like this is that one of the trickiest parts of threads is keeping one thread from corrupting memory used by another thread. Perhaps something is corrupted in the heap so that when you calculate block_size, you're getting not the size you really want, but something really, really huge.

    Just a possibility.

    But the answer to your main question, once again, is that using threads raises no special requirements when using malloc() or free().
    --
    Bill

    Old age and treachery will overcome youth and skill.

  3. #3
    Just Joined!
    Join Date
    Dec 2008
    Posts
    2
    You mentioned interesting point - how can we make sure that memory of one thread does not interfere with another one?

  4. #4
    Linux Engineer wje_lf's Avatar
    Join Date
    Sep 2007
    Location
    Mariposa
    Posts
    1,192
    how can we make sure that memory of one thread does not interfere with another one?
    Don't write any incorrect code.

    Scary, I know. That's why I only use threads when I need them, and then keep the software as simple as possible.
    --
    Bill

    Old age and treachery will overcome youth and skill.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...