derefernecing a pointer changes its value

For any pointer or array p and index i, the expression *(p + i) is exactly equal to p[i].

Now if we do this transformation of *(vec->ptr + (ELEMENT_SIZE * index) we get vec->ptr[ELEMENT_SIZE * index]. Which is probably not what you had in mind.

Assuming that sizeof(int) (what ELEMENT_SIZE expands to) is 4 (very common) then attempting to use index 2 will actually use index 8 (4 * 2). Which is out of bounds of your allocated memory (as it only contains 5 elements), and leads to undefined behavior.

The solution is simple: Don’t multiply with ELEMENT_SIZE when accessing elements of your array.

You have another two very serious errors as well:

realloc(vec->ptr, ELEMENT_SIZE * (vec->len + 1))
*(vec->ptr + (ELEMENT_SIZE * vec->len)) = val;

Because the first line is missing the semicolon, the statement becomes

realloc(vec->ptr, ELEMENT_SIZE * (vec->len + 1)) * (vec->ptr + (ELEMENT_SIZE * vec->len)) = val;

And that doesn’t make any sense.

The second problem, besides the missing semicolon, is that realloc can allocate a new memory area, which it then returns a pointer to. That would make the old pointer invalid as it then points to memory that you no longer own. Always use what realloc returns.

But also note that realloc can return NULL, in which case the old pointer remains valid, so always use a temporary variable:

int *new_ptr = realloc(vec->ptr, ELEMENT_SIZE * (vec->len + 1));
if (new_ptr == NULL)
    // TODO: Handle error
vec->ptr = new_ptr;
vec->ptr[vec->len] = val;

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top