Search code examples
cdynamic-memory-allocationmemcpyfunction-definition

Error using memcpy : "Access violation reading location 0x0000000000000000"


I am trying to write something similar to std::vector but in c to store a bunch of mathematical vectors.

Here is the line that is casing the error.

pVl->pData = memcpy(pNewData, pVl->pData, sizeof(pVl->pData));

My Intention: Copy data from pVl->pData to pNewData. Then assign the return value, which is the pointer to start of the newly copied data memory and assign it to pVl->pData. I am not sure what I am doing wrong.

MRE:

#include <stdlib.h>
#include <string.h>

typedef enum R_Code { R_OK, R_WARNING, R_FAIL, R_FATAL } R_Code;

struct Vector2_s
{
    float x;
    float y;
} const Default_Vector2 = { 0.0f, 0.0f };

typedef struct Vector2_s Vector2;

struct Vector2List_s
{
    //current capacity of the List
    size_t capacity;

    //current size of the list 
    size_t size;

    //data buffer 
    Vector2* pData;

} const Default_Vector2List = { 0, 0, NULL };

typedef struct Vector2List_s Vector2List;

R_Code Vector2List_ReAllocateMem(Vector2List* pVl) {
    if (pVl->capacity == 0) {
        pVl->capacity++;
    }

    Vector2* pNewData = malloc(pVl->capacity * 2 * sizeof(Vector2));
    if (pNewData == NULL) {
        return R_FAIL;
    }

    pVl->capacity *= 2;
    pVl->pData = memcpy(pNewData, pVl->pData, sizeof(pVl->pData));//EXPECTION THROWN IN THIS LINE
    free(pNewData);
    return R_OK;
}

R_Code Vector2List_PushBack(Vector2List* pVl, const Vector2 v) {
    if (pVl->size == pVl->capacity) {
        R_Code rcode = Vector2List_ReAllocateMem(pVl);
        if (rcode == R_FAIL) {
            return rcode;
        }
    }

    pVl->pData[pVl->size] = v; 
    pVl->size++;
    return R_OK;
}

int main() {

    Vector2List vl = Default_Vector2List;
    Vector2List_PushBack(&vl, Default_Vector2);
    return 0;
}

Solution

  • Within the function Vector2List_ReAllocateMem you allocated dynamically memory

    Vector2* pNewData = malloc(pVl->capacity * 2 * sizeof(Vector2));
    

    then in this statement

    pVl->pData = memcpy(pNewData, pVl->pData, sizeof(pVl->pData));
    

    you are using the null pointer pVl->pData as a source of data that invokes undefined behavior.

    Moreover you freed the allocated memory.

    free(pNewData);
    

    Also using this expression sizeof(pVl->pData) does not make a sense.

    It seems what you need is the following

    pVl->pData = pNewData;
    

    Though if you are going to reallocate memory then instead of malloc you need to use realloc.

    You need to rewrite the function entirely.