Hello,

I am having a memory allocation error, and will post some code, but some context first is important. My program, on certain problem instances, will run out of memory, regardless of any type of memory leaks which may or may not occur. I am purposefully pushing the limits of my machine, and will always be in the situation where it is possible that memory will run out no matter how I update my code.

That said, here is the function causing me problems (I will post my solution to it later):
(on a side note, I know I should be using C++ for this - it's a really, really long story. this is on my to do list but I need this code to work asap. however, if you have details as to why new is a better choice than malloc, I would love to know this - i only know this to be fact).

Code:
typedef struct Tree_Node{
  int size;
  struct Tree_Node** children;
}

Tree_Node* New_Child( int size){

  int i;
  Tree_Node* node = malloc(sizeof(Tree_Node));
  node->size = size;

  if( size != 0 )
    node->children = malloc(sizeof(Tree_Node)*size);
  else
    node->children = NULL;

  for(i = 0; i < size; i++)
    node->children[i] = NULL;

  return node;

}
The code will seg fault in the for loop. Gdb showed that even though size was non-zero, node->children was NULL, causing the seg fault.

This is my fix:


Code:
typedef struct Tree_Node{
  int size;
  struct Tree_Node** children;
}

Tree_Node* New_Child( int size){

  int i;
  Tree_Node* node = malloc(sizeof(Tree_Node));
  node->size = size;

  if( size != 0 )
  {
    node->children = malloc(sizeof(Tree_Node)*size);
    if( node->children == NULL )
    {
      perror("Memory not allocated in New_Child. Exiting\n");
      exit(0);
    }
  }
  else
    node->children = NULL;

  for(i = 0; i < size; i++)
    node->children[i] = NULL;

  return node;

}
I'm assuming that what's going on is that malloc is returning a NULL pointer when it is out of memory, but this is counter-intuitive as normally when my program runs out of memory Ubuntu will kill the process. I did not have the chance to check if size had been altered by the time new->children was allocating memory. Could it be that my heap is growing too large and overwriting the size variable in the stack? If this were the case, it seems like Ubuntu would kill the process before it got to this point (I'm just conjecturing - I know very little to nothing about operating systems).

All this aside, under what conditions does malloc return a NULL pointer?


Any help would be appreciated. Cheers,

Rob