gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:44:09 25 4
gpt4 key购买 nike

所以我遇到的第一个 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;
}

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

编辑框架.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];

关于c - strncpy 访问冲突读取位置...输入到链表时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44696526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com