我是一个很新的链表,需要一点帮助。目前我收到这个错误"
0x0FD940C1 (msvcr120 .dll)中的未处理异常ConsoleApplication1.exe: 0xC0000005:访问违规读取位置0 x00000001。
程序试图做的是取一个文件,遍历它并创建一个链表,每个节点由字符串值和指向下一个节点的节点指针组成。我已经遵循了多个教程,我不确定问题是什么。如果有人能帮忙,那就太好了。
下面是我的代码:#ifdef _WIN32
#define _CRT_SECURE_NO_DEPRECATE
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFF_SIZE 300
typedef struct node {
char stringDat[BUFF_SIZE];
struct node* next;
} NODE;
int main(int argc, char** argv) {
FILE* fp;
FILE* fpLogFile;
char* fileLoc = "C:\Users\David\Desktop\data.dat";
char* logFile = "C:\Users\David\Desktop\log.txt";
char buff[BUFF_SIZE];
int i, nodeCnt;
if ((fp = fopen(fileLoc, "rb+")) == NULL) {
printf("FILE OPEN ERROR ON EXISTING FILEn");
exit(1);
}
if ((fpLogFile = fopen(logFile, "w")) == NULL) {
printf("Error opening log filen");
exit(1);
}
// root node
NODE* root = NULL;
// provide memory for root node
root = malloc(sizeof(NODE));
if (root == NULL){
return 1;
}
fprintf(fpLogFile, "%sn", "ROOT MALLOC");
nodeCnt = 1;
// assign values to root node
root->next = NULL;
fprintf(fpLogFile, "%sn", "ROOT Next = 0");
strcpy(root->stringDat, fread(buff, 20, 1, fp));
fprintf(fpLogFile, "%sn", "ROOT buff");
// set curr to root node
NODE* curr = root;
fprintf(fpLogFile, "%sn", "Curr = ROOT");
while (fread(buff, 20, 1, fp) != NULL) {
// navigate to last node in list
while (curr->next != NULL) {
curr = curr->next;
}
fprintf(fpLogFile, "%sn", "Curr = last node");
// Create node at end of list
curr->next = malloc(sizeof(NODE));
fprintf(fpLogFile, "%sn", "Malloc new Node");
nodeCnt++;
// move current node to last node
curr = curr->next;
if (curr == 0) {
fprintf(fpLogFile, "%sn", "Out of memory");
return 0;
}
// assign val to current stringDat
strcpy(curr->stringDat, buff);
fprintf(fpLogFile, "%s %d %p %dn", curr->stringDat, strlen(curr->stringDat), curr->next, nodeCnt);
for (i = 0; i < BUFF_SIZE; i++) {
buff[i] = 0;
}
}
while ((curr = root) != NULL) { // set curr to head, stop if list empty.
root = root->next; // advance head to next element.
free(curr); // delete saved pointer.
}
fclose(fp);
fclose(fpLogFile);
return 0;
}
This:
strcpy(root->stringDat, fread(buff, 20, 1, fp));
没有意义,应该触发编译器警告。
strcpy()
的第二个参数是一个字符串指针,但fread()
返回size_t
(它成功读取的"元素"的数量)。当它在这里成功时,它将返回1
,这将触发您得到的错误。
你的意思:
if(fread(buff, 20, 1, fp) == 1)
strcpy(root->stringDat, buff);