无法访问 C 中地址处的内存

标签 c linked-list

我有一个包含一串字符的节点链表。该程序从 stdin 读取字符,直到它到达一个新行,一旦它到达它就把这个字符串放入列表的一个新节点。

我已经对程序中涉及的不同步骤进行了一些调试,并且可以看到正在正确创建的节点列表。

enter image description here

但是,如果我单步执行代码,printf 语句似乎没有做任何事情。如果我不单步执行而只是运行代码,我会得到:

无法访问地址为 0x2e666564 的内存

无法访问地址为 0x2e666564 的内存

无法访问地址为 0x2e666564 的内存

我的源代码是:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Node {
    char *string;
    struct Node *next;
} List;

List *addNode(List *currentList, char *character)
{
    List *tempList = calloc(1, sizeof(List));
    tempList->string = strdup(character);
    tempList->next = currentList;

    return tempList;
}

void printList(List *currentList)
{
    while (currentList != NULL)
    {
        printf("%s", currentList->string);
        currentList = currentList->next;
    }
}

int main ()
{
    char currentCharacter;
    char *currentString;
    List *mainList = NULL;

    do 
    {
        currentCharacter = getchar();
        if (currentCharacter == '\n')
        {
            mainList = addNode(mainList, currentString);
            currentString[0] = '\0';
        } else {
            strcat(currentString, &currentCharacter);
        }
    } while (currentCharacter != '.');

    mainList = addNode(mainList, currentString);


    printList(mainList);

    return 0;
}

最佳答案

您在无效指针上调用 strcat。

像这样的东西会起作用:

char currentString[128];
currentString[0] = '\0';

currentCharacter 不是以 null 结尾的,因此 strcat 将不起作用。请改用 strncat。

关于无法访问 C 中地址处的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8302029/

相关文章:

c - LLVM 即时编译 : how to disable automatic function resolve?

无需使用标准协议(protocol)即可进行大数据包交换的 CAN

delphi - Delphi 中的 TStringList、动态数组还是链接列表?

c - 将内存分配给包含结构的节点

c - GStreamer:没有这样的文件或目录

c - 函数内部的 for 循环在 C 中似乎无法正常工作

C 调用约定 : who cleans the stack in variadic functions vs normal functions?

c - 创建链表时出现段错误

c - 链表 IPC C 语言

c++ - c++数据输入并在列表的结构中读回数组