gpt4 book ai didi

c - 为什么 fgets 会覆盖看似不相关的变量?

转载 作者:行者123 更新时间:2023-11-30 18:47:46 25 4
gpt4 key购买 nike

我在学习 C 的同时正在做一个小项目,并且偶然发现了一个慢慢让我发疯的问题。我有一个结构体,其中包含指向相同类型的其他结构体的指针,以及一个用于从 stdin 获取字符串的输入数组

typedef struct Node
{
char *objectName;
char *question;
struct Node *yesPtr;
struct Node *noPtr;
}Node;

int main(int argc, char **argv)
{
Node *rootNode = initialise(LAUNCH_TYPE);
Node *currentNode = rootNode;
int quit = 0;
char input[INPUT_SIZE];
while (quit == 0)
{
...

但是,在尝试使用 fgets 接受输入时,它将覆盖看似不相关的变量。

fgets(input,INPUT_SIZE,stdin);
input[strcspn(input, "\n")] = '\0';
pNew->objectName = input; //Code works here, input behaves as expected..
printf(pNew->objectName); //..and this is correct
printf("Please type a question!\n");

fgets(input,INPUT_SIZE,stdin); //However, this line overwrites pNew->objectName to its input
input[strcspn(input, "\n")] = '\0';
currentNode->question = input; //While this line still functions as expected
printf(pNew->objectName); //This will now (incorrectly) print out the string that had just been entered

即使使用完全独立于结构的变量,也会出现完全相同的问题。

fgets(input,INPUT_SIZE,stdin);
input[strcspn(input, "\n")] = '\0';
char *newObject = input; //Even when replacing the pointer with another variable
printf(newObject);
printf("Please type a question!\n");

fgets(input,INPUT_SIZE,stdin); //This line will overwrite the new variable too
input[strcspn(input, "\n")] = '\0';
currentNode->question = input;
pNew->objectName = newObject;
printf(pNew->objectName); //And results in the same problem

我多年来一直在解决这个问题,但在网上找不到任何解决方案,尽管这可能只是一些奇怪的 malloc 错误,有人知道为什么会发生这种情况吗?

最佳答案

当你这样做时:

pNew->objectName = input;

您将input 数组的地址分配给objectName。您没有制作副本。

然后当你这样做时:

currentNode->question = input;

您再次将输入的地址分配给该字段。所以现在pNew->objectNamecurrentNode->question都指向同一个地方,即input。因此,只要输入发生变化,当您使用上述任一变量时,它都会反射(reflect)出来。

要复制字符串,请使用 strdup:

pNew->objectName = strdup(input);

这会为字符串的副本动态分配内存,将字符串复制到新分配的内存,并返回该内存的地址。

当您清理包含的结构时,请务必对每个对象调用 free

关于c - 为什么 fgets 会覆盖看似不相关的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47539573/

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