Search code examples
cstructmallocdynamic-memory-allocationc-strings

C : Access violation reading location with malloc


I want to allocate memory to structures in function and assign the values given as parameters to the function. My code:

linkedList.c

FrameNode* createFrameNode(char name[MAX_NAME], int duration, char path[MAX_PATH])
{
    Frame* newFrame = malloc(sizeof(Frame));
    FrameNode* newNode = malloc(sizeof(FrameNode));

    // Copy name
    strcpy(newFrame->name, name);

    // Add duration and path
    newFrame->duration = duration;
    strcpy(newFrame->path, path);

    // Attach new frame to the new node
    newNode->frame = newFrame;
    newNode->next = NULL;

    return newNode;
}

I get an error back:

Exception thrown at 0x00007FFF18C4D215 (ucrtbased.dll) in C_Project.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.

If I try to get any memory related to the structs. Can you tell what is wrong from my code?

The structs in linkedList.h

// Frame struct
typedef struct Frame
{
    char* name;
    unsigned int duration;
    char* path;
} Frame;


// Link (node) struct
typedef struct FrameNode
{
    Frame* frame;
    struct FrameNode* next;
} FrameNode;

Solution

  • The data member name of the structure struct Frame has the pointer type char *

    // Frame struct
    typedef struct Frame
    {
        char* name;
        unsigned int duration;
        char* path;
    } Frame;
    

    After this allocation of memory for an object of the type struct Frame

    Frame* newFrame = malloc(sizeof(Frame));
    

    the data member name has an indeterminate value.

    So this call of strcpy

    // Copy name
    strcpy(newFrame->name, name);
    

    invokes undefined behavior.

    You need to allocate memory where you are going to copy the string pointed to by the pointer name like for example

    // Copy name
    newFrame->name = malloc( strlen( name ) + 1 );
    strcpy(newFrame->name, name);
    

    The same problem exists for the data member path. That is you need to allocate a character array where you are going to copy the string pointed to by the pointer path.

    In general you should check that all memory allocations were successful.

    Pay attention to that these parameter declarations char name[MAX_NAME] and char path[MAX_PATH] are adjusted by the compiler to the declarations char *name and char *path. These parameters should be declared with qualifier const because the passed strings are not changed within the function.

    FrameNode* createFrameNode(const char name[MAX_NAME], int duration, const char path[MAX_PATH]);