0

I have this portion of c++ code, below there are two lines using malloc and I want to change it to new notation.

struct CodingTree* createCodingTree(unsigned int capacity){ 

    struct CodingTree* cTree = (struct CodingTree*)malloc(sizeof(struct cTree));
    
    cTree->size = 0; 

    cTree->capacity = capacity; 

    cTree->array = (struct BinaryNode**)malloc(cTree-> 
capacity * sizeof(struct BinaryNode*)); 
    return cTree; 
}

For the first one, I've changed :

struct CodingTree* cTree = (struct CodingTree*)malloc(sizeof(struct cTree));

to

CodingTree* cTree = new CodingTree(); 

And seems like it's working, but for the second one, I have no idea what would be the equivalent new.

For reference, adding the CodingTree and BinaryNode structures.

struct BinaryNode{
    char symbol;
    unsigned int count;
    struct BinaryNode *left, *right;
    BinaryNode(char symbol, unsigned int count){
        this->symbol = symbol;
        this->count = count;
        left =0;
        right =0;
    }
};


struct CodingTree { 

    unsigned int size; 

    unsigned int capacity; 

    BinaryNode** array; 
}; 
Valerin
  • 133
  • 1
  • 6
  • 5
    This is a case of not seeing the forest for the trees. Has it occurred to you that most of this scaffolding is reinventing a well-known wheel called a "vector"? Instead of sinking time into merely replacing `malloc` with `new`, instead replacing most of this stuff with `std::vector`, and calling it a day, is going to be much, much simpler. Nothing to `malloc` or `new`, the vector will do everything for you. Your `CodingTree` will have just one member `std::vector`. All code that deals with `capacity` and `size` gets flushed down the drain. The End. – Sam Varshavchik Oct 11 '20 at 03:32
  • 1
    Change `cTree->array = (struct BinaryNode**)malloc(cTree-> capacity * sizeof(struct BinaryNode*)); ` to `cTree->array = new BinaryNode*[cTree->capacity];` – Andreas Wenzel Oct 11 '20 at 03:34
  • 1
    If allocation was with `malloc()`, then deallocation will be with `free()`, you can't just change `malloc()` to `new()` without also changing the deallocation. – David C. Rankin Oct 11 '20 at 03:53

1 Answers1

3

And seems like it's working, but for the second one, I have no idea on what would be the equivalent new for reference adding the CodingTree and BinaryNode structures.

It seems like what you want is:

cTree->array = new BinaryNode*[cTree->capacity];

Now this requires you to also change free into delete (and delete[] for arrays). delete/delete[] will call the proper destructor whereas free won't. Calling free on memory allocated with new is undefined behaviour; there's no guarantee that malloc and new allocate from same heap.


Though it's better if you follow the advice given in the comment, to use std::vector for this.

Andreas DM
  • 10,685
  • 6
  • 35
  • 62