C链接列表:访问冲突读取位置0x00000001

时间:2016-11-14 19:08:59

标签: c memory-management linked-list

我对链表很新,需要一些帮助。目前我收到此错误"

  

0x0FD940C1(msvcr120d.dll)中的未处理异常   ConsoleApplication1.exe:0xC0000005:访问冲突读取位置   00000001

程序尝试做的是获取文件并迭代它并创建链接列表,每个节点由字符串值和指向下一个节点的节点指针组成。我已经遵循了多个教程,我不确定是什么问题。如果有人可以提供帮助,那就太棒了。

以下是我的代码:

#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 FILE\n");
        exit(1);
    }

    if ((fpLogFile = fopen(logFile, "w")) == NULL) {
        printf("Error opening log file\n");
        exit(1);
    }

    // root node
    NODE* root = NULL;

    // provide memory for root node
    root = malloc(sizeof(NODE));
    if (root == NULL){
        return 1;
    }
    fprintf(fpLogFile, "%s\n", "ROOT MALLOC");
    nodeCnt = 1;

    // assign values to root node
    root->next = NULL;
    fprintf(fpLogFile, "%s\n", "ROOT Next = 0");

    strcpy(root->stringDat, fread(buff, 20, 1, fp));
    fprintf(fpLogFile, "%s\n", "ROOT buff");

    // set curr to root node
    NODE* curr = root;
    fprintf(fpLogFile, "%s\n", "Curr = ROOT");

    while (fread(buff, 20, 1, fp) != NULL) {

        // navigate to last node in list
        while (curr->next != NULL) {
            curr = curr->next;
        }

        fprintf(fpLogFile, "%s\n", "Curr = last node");

        // Create node at end of list
        curr->next = malloc(sizeof(NODE));
        fprintf(fpLogFile, "%s\n", "Malloc new Node");
        nodeCnt++;
        // move current node to last node
        curr = curr->next;

        if (curr == 0) {
            fprintf(fpLogFile, "%s\n", "Out of memory");
            return 0;
        }
        // assign val to current stringDat
        strcpy(curr->stringDat, buff);

        fprintf(fpLogFile, "%s     %d    %p    %d\n", 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;

}

1 个答案:

答案 0 :(得分:3)

此:

strcpy(root->stringDat, fread(buff, 20, 1, fp));

毫无意义,应该触发编译器警告。

strcpy()的第二个参数是一个字符串指针,但fread()返回size_t(&#34;元素的数量&#34;它成功读取)。当它在此处成功时,它将返回1,这将触发您获得的错误。

你的意思是:

if(fread(buff, 20, 1, fp) == 1)
  strcpy(root->stringDat, buff);