잠시 동안 프로그래밍을 해왔지만 C에 익숙하지 않습니다. 테스트해야하는 ansi C에서이 링크 된 목록 구현이 있습니다. 나는 문제를 잘못된 글쓰기 문제로 좁혔다. 나는 Valgrind의를 통해 코드를 실행하고 다음과 같은 출력을받은 :strcpy로 유효하지 않은 쓰기
==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 인터페이스를 사용하는 것입니다. InitLinkedLists, AddToBackOfList 및 DestroyList는 모두 해당 인터페이스에 정의되어 있습니다.
#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;
을 정의 : 코멘트 (WhozCraig)에 설명 된대로
또는 :
다음을 사용하여 할당해야합니까? – cnicutar
'p = malloc (sizeof p)'는 항상 잘못되었습니다. – melpomene
typedef struct ElementStructs { /* 응용 프로그램 정의 */ int index; char str [100]; } ElementStructs; – user1935333