gpt4 book ai didi

c - 使用 strcpy 写入无效

转载 作者:行者123 更新时间:2023-12-04 05:17:31 24 4
gpt4 key购买 nike

我已经编程了一段时间,但我是 C 新手。我在 ansi C 中有这个链表实现,我需要测试它。我已将问题缩小到无效写入的问题。我通过 Valgrind 运行代码并收到以下输出:

==18131== Invalid write of size 1
==18131== at 0x4C2C0CC: __GI_strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64 linux.so)
==18131== by 0x40089B: main (in /home/btm7984/hw3/TestList)
==18131== Address 0x51f1388 is 0 bytes after a block of size 8 alloc'd
==18131== at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18131== by 0x400880: main (in /home/btm7984/hw3/TestList)
==18131==
==18131== Invalid write of size 1
==18131== at 0x4C2C0DF: __GI_strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18131== by 0x40089B: main (in /home/btm7984/hw3/TestList)
==18131== Address 0x51f138e is 6 bytes after a block of size 8 alloc'd
==18131== at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18131== by 0x400880: main (in /home/btm7984/hw3/TestList)
==18131==
--18131-- VALGRIND INTERNAL ERROR: Valgrind received a signal 11 (SIGSEGV) - exiting
--18131-- si_code=1; Faulting address: 0x6D4FCAA; sp: 0x402bdae00

我可以从中确定的只是我分配了错误的东西。我认为它必须与我的 strcpy 线有关。我真的不知道如何回答这个问题。下面是我对 LinkedLists 接口(interface)的使用。 InitLinkedLists、AddToBackOfList 和 DestroyList 都在该接口(interface)中定义。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "LinkedLists.h"

int main(int argc, char *argv[]) {

FILE *fp;
char tmpString[100];
LinkedLists *ListPtr = malloc(sizeof(LinkedLists));
ElementStructs *DataPtr;
LinkedListNodes* curr = malloc(sizeof(LinkedListNodes));
int counter = 0;
int Done = 0;

InitLinkedList(ListPtr);
fp = fopen(argv[1], "r");
if (!fp){
fprintf(stderr,"%s Cannot open file %s\n", argv[0], argv[1]);
exit(1);
}
do{
fscanf(fp,"%s",tmpString);
if (!feof(fp)) {
DataPtr = malloc(sizeof(DataPtr));
printf("%d %d : %d\n",counter,(int)strlen(DataPtr->str),(int)strlen(tmpString));
strcpy(DataPtr->str,tmpString);
DataPtr->index=counter;
AddToBackOfLinkedList(ListPtr, DataPtr);
counter++;
Done = 1;
} else {
Done = 0;
}
}while (Done);

总之,我认为 strcpy 导致无效写入,我不知道为什么。

任何帮助将不胜感激。提前致谢。

编辑: ElementStructs 定义如下:
typedef struct ElementStructs
{
/* Application Specific Definitions */
int index;
char str[100];
} ElementStructs;

最佳答案

问题出在以下语句中:

DataPtr = malloc(sizeof(DataPtr));

您只分配足够的内存来保存指针而不是完整的结构。

您应该使用以下方式分配:
DatapPtr = malloc(sizeof(ElementStructs));

或者,如评论(WhozCraig)中所述:
DatapPtr = malloc(sizeof(*DataPtr));

关于c - 使用 strcpy 写入无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14075415/

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