gpt4 book ai didi

c - 想知道什么时候用 C 语言免费打电话

转载 作者:行者123 更新时间:2023-12-01 06:14:49 25 4
gpt4 key购买 nike

编辑 看来这只是示例代码错误的情况。谢谢你解决这个问题,SO。

查看以下来自 http://staff.um.edu.mt/csta1/courses/lectures/csa2060/c8a.html 的代码/引述

//f.c    
#include <stdio.h>
#include <stdlib.h>

char *foo(char *);

main() {
char *a = NULL;
char *b = NULL;

a = foo("Hi there, Chris");
free(a);

b = foo("Goodbye");
free(b);

printf("From main: %s %s\n", a, b);
}

char *foo(char *p) {
char *q = (char *)malloc(strlen(p)+1);
strcpy(q, p);
printf("From foo: the string is %s\n", q);
return q;
}

If free(b) is omitted, then “Goodbye” can be seen to be written to the location of “Hi there, Chris”.

我不明白为什么在使用 printf() 语句中释放的变量之前必须先调用 free(事实上,在我看来,首先释放内存似乎会使它失败)。

如果这是重复,我深表歉意,但在搜索/阅读我能找到的内容后,我仍然一头雾水。代码和报价来自这里:http://staff.um.edu.mt/csta1/courses/lectures/csa2060/c8a.html

编辑 看来这只是示例代码错误的情况。谢谢你解决这个问题,SO。

最佳答案

当你不需要再次使用内存时调用free()

您的 printf() 在您释放了两个字符串之后出现,因此当您尝试打印字符串时会调用“未定义行为”(UB)。 main()ab 获得相同地址的可能性不大,在这种情况下,您只能当然是存储在空间中的两个字符串之一。但这仍然是 UB,任何事情都可能发生。

您应该只在 main() 中的 printf() 之后调用 free()

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

char *foo(char *);

int main(void)
{
char *a = NULL;
char *b = NULL;

a = foo("Hi there, Chris");
b = foo("Goodbye");

printf("From main: %s %s\n", a, b);

free(a); // Now it is safe to free the memory
free(b);
return 0;
}

char *foo(char *p)
{
char *q = (char *)malloc(strlen(p)+1);
strcpy(q, p);
printf("From foo: the string is %s\n", q);
return q;
}

关于c - 想知道什么时候用 C 语言免费打电话,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7636731/

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