Apostolos\’ Daily Plate

Don’t use malloc with C++

Posted in Πληροφορική by asyropoulos on 8 Δεκεμβρίου, 2012

OK this may not be news for experienced C++ programmers, but as a word of advice never use malloc in C++ programs. In particular, if one wants to implement dynamic data structures using pointers, she should use new instead of malloc. For example, consider the following declarations:

typedef struct {
  string env_name;
  int lineno;
} env_data;

struct node {
  env_data data;
  struct node *link;
};

typedef struct {
  struct node *head;
  struct node *list_node;
} Stack;

Then the following is not the way to allocate memory for a node

stack->list_node = (node *) malloc(sizeof(node));

The proper way to do this is simply:

stack->list_node = new node;

As an exercise I wrote a simple program that utilized a stack and initally I used malloc to create nodes, but the program crashed most of the times. When I replaced malloc with new, the program stopped crashing and gave the expected results. So don’t use malloc in C++, it’s for C programmers only.