strncpy access violation reading location... 输入链表时

strncpy access violation reading location... when inputting into linked list

所以我遇到的第一个 strncpy 基本上得到了 运行 次错误: "access violation reading location" 我不确定为什么,因为我确实为 "addedFrame".

分配了内存

代码:

 void addFrame(link_t **list)
{
    bool validFrame = true;
    char frameName[MAX_NAME_SIZE] = { 0 };
    char framePath[MAX_PATH_SIZE] = { 0 };
    link_t* currentFrame = *list;

    link_t* addedFrame = (link_t*)malloc(sizeof(link_t));
    addedFrame->frame = (frame_t*)malloc(sizeof(frame_t));
    // Checking if malloc was succesfull
    if (!addedFrame->frame)
    {
        printf("Couldn't allocate memory\n");
        exit(-1);
    }

    // If in case of the head being null
    if (*list)
    {

        do
        {
            printf("Enter frame name: ");
            fgets(frameName, MAX_NAME_SIZE, stdin);

            // Resetting current frame back to the head
            currentFrame = *list;

            while (currentFrame->next != NULL)
            {
                if (!strcmp(frameName, currentFrame->next->frame->name))
                {
                    printf("A frame with the entered name already exists\n");
                    validFrame = false;
                }
                currentFrame = currentFrame->next;
            }

        } while (validFrame == false);

        currentFrame->next = addedFrame;

    }
    else
    {
        printf("Enter frame name: ");
        fgets(frameName, MAX_NAME_SIZE, stdin);
        frameName[strcspn(frameName, "\n")] = 0; // Removing the "\n" character and adding the terminating null
        *list = addedFrame;
    }

    strncpy(addedFrame->frame->name, frameName, MAX_NAME_SIZE);

    printf("Enter frame duration (in miliseconds): ");
    scanf("%d", &addedFrame->frame->duration);
    getchar(); // Clearing the buffer


    printf("Enter frame path: ");
    fgets(framePath, MAX_PATH_SIZE, stdin);
    framePath[strcspn(framePath, "\n")] = 0;
    strcpy(addedFrame->frame->path, framePath);
    printf("\n");


    addedFrame->next = NULL;
}

上面的函数应该使用用户输入的值在列表的末尾插入一个新节点。

编辑 Frame.h:

#ifndef FRAME_H
#define FRAME_H

#include <stdio.h>

struct Frame
{
    char            *name;
    unsigned int    duration;
    char            *path;  // may change to FILE*
};

typedef struct Frame frame_t;


#define MAX_PATH_SIZE (256)
#define MAX_NAME_SIZE (50)

#endif //FRAME_H

和linkedList.h:

#ifndef LINKEDLISTH
#define LINKEDLISTH


#include "Frame.h"

struct Link
{
    frame_t *frame;
    struct Link *next;
};

typedef struct Link link_t;
#endif

根据你评论里说的,addedFrame->frame->name的类型是char *。这就是你出错的原因。

必须分配一个char *,直到分配到它之前它只是一个指向任何内容的指针。

您可以:

  • 使用malloc

    为其分配内存
    link_t* addedFrame = malloc(sizeof(link_t));
    addedFrame->frame = malloc(sizeof(frame_t));
    addedFrame->frame->name = malloc(MAX_NAME_SIZE);     // <---
    
  • 将其定义为字符数组而不是struct Frame

    中的char *
    char *name; ---> char name[MAX_NAME_SIZE];