Home > Blockchain >  does dynamically allocation structs in cpp require redefining elements?
does dynamically allocation structs in cpp require redefining elements?

Time:12-29

Trying to implement the add function in dynamic list, recursively. The code is self-explanatory:

struct list {
    int value;
    list* next = NULL; // is this valid?
};

list head;

void add(list* cur, int value) {
    if (cur->next) {
        add(cur->next, value);
        return;
    }
    cur->next = (list*)(malloc(sizeof(list)));
    cur->next->value = value;
    cur->next->next = NULL; // withouth this line, the program errors out after two calls to the function add
}

int main() {
    for (int i = 0; i < 50; i  ) 
        add(&head, i);
}

After seeing the debugger, I realized that calling malloc wasn't initiating "next" with NULL as specified in the defininition of the list struct.

CodePudding user response:

As noted in comments, malloc does not initialize anything. It simply grabs a chunk of memory big enough for a list struct. Now, that might mean that struct has next set to NULL, or it might not.

That is why you're having to explicitly initialize it to NULL as that prevents undefined behavior when accessing that member.

If you use new to handle dynamic memory allocation, then the next member is initialized to NULL.

    cur->next = new list;

Including this use of malloc, your code is very C-ish, and there are numerous improvements C will allow you to make.

  • Related