简体   繁体   中英

I don't think I fully understand realloc, can someone explain to me why a realloc in my code sometimes fails but sometimes doesn't

I'm writing a very simple list datatype in C (its horrendously inefficient, but it works) for this larger program but depending on how I use the code, I sometimes get segmentation faults but if my input data is slightly different the code fine.

The offending section is this:

struct Vec {
        int size;
        Node* ptr;
};

void push_to_vec(struct Vec* root, Node to_push) {
        root -> size ++;
        root -> ptr = realloc(root -> ptr, root -> size);
        root -> ptr[root -> size - 1] = to_push;
}

I tried debugging this code using print stamens and then with lldb, and it seems like the realloc call in the push_to_vec function is the line that fails.

Any help would be appreciated and thanks in advance.

You're not allocating enough space.

The second parameter to realloc is the size in bytes to allocate, not the number of array elements. As a result, you're writing past the end of allocated memory invoking undefined behavior

You need to multiply the number of elements by the element size.

root->ptr = realloc(root->ptr, root->size * sizeof(*root->ptr));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM