所以我基本上遇到的第一个strncpy会出现运行时错误:"访问冲突读取位置"我不确定为什么,因为我确实为"添加帧"分配了内存。
法典:
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 memoryn");
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 existsn");
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;
}
上面的函数应该在列表的末尾插入一个新节点,其中包含用户输入的值。
编辑帧:
#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];