strncpy访问冲突读取位置...输入到链表时

时间:2017-06-22 10:16:09

标签: c linked-list strncpy

所以我遇到遇到的第一个strncpy基本上会遇到运行时错误: “访问违规阅读位置” 我不确定为什么因为我确实为“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;
}

上述函数应该在列表末尾插入一个新节点,并带有用户输入的值。

EDIT 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

1 个答案:

答案 0 :(得分:0)

根据您在评论中所说的内容,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);     // <---
    
  • 将其定义为字符数组,而不是char *

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