Does C allocate memory automatically for me?

前端 未结 8 2114
情话喂你
情话喂你 2020-12-19 14:18

I have been writing C for only a scant few weeks and have not taken the time to worry myself too much about malloc(). Recently, though, a program of mine return

8条回答
  •  天涯浪人
    2020-12-19 14:47

    Short answer: It isn't allocated for you.

    Slightly longer answer: The subcells pointer is uninitialized and may point anywhere. This is a bug, and you should never allow it to happen.

    Longer answer still: Automatic variables are allocated on the stack, global variables are allocated by the compiler and often occupy a special segment or may be in the heap. Global variables are initialized to zero by default. Automatic variables do not have a default value (they simply get the value found in memory) and the programmer is responsible for making sure they have good starting values (though many compilers will try to clue you in when you forget).

    The newCell variable in you function is automatic, and is not initialized. You should fix that pronto. Either give newCell.subcells a meaningful value promptly, or point it at NULL until you allocate some space for it. That way you'll throw a segmentation violation if you try to dereference it before allocating some memory for it.

    Worse still, you are returning a Cell by value, but assigning it to a Cell * when you try to fill the subcells array. Either return a pointer to a heap allocated object, or assign the value to a locally allocated object.

    A usual idiom for this would have the form something like

    Cell* makeCell(dim){
      Cell *newCell = malloc(sizeof(Cell));
      // error checking here
      newCell->subcells = malloc(sizeof(Cell*)*dim); // what if dim=0?
      // more error checking
      for (int i=0; isubCells[i] = makeCell(dim-1);
        // what error checking do you need here? 
        // depends on your other error checking...
      }
      return newCell;
    }
    

    though I've left you a few problems to hammer out..

    And note that you have to keep track of all the bits of memory that will eventually need to be deallocated...

提交回复
热议问题