gpt4 book ai didi

C char 数组、指针、malloc、free

转载 作者:行者123 更新时间:2023-11-30 21:34:10 31 4
gpt4 key购买 nike

我正在尝试理解指针,我有这个简单的例子

void third(char ****msg) {
***msg = malloc(5 * sizeof (char));
printf("\nthe msg in third is :%s ", ***msg);
strcpy(***msg, "third");
printf("\nthe msg in third after is: %s", ***msg);
// free(***msg);
}

void change(char***msg) {
**msg = malloc(5 * sizeof (char));
printf("\nthe msg in change is :%s ", **msg);
strcpy(**msg, "change");
printf("\nthe msg in change after is: %s", **msg);
third(&msg);
// free(**msg);
}

void test(char ** msg) {
*msg = malloc(5 * sizeof (char));
printf("\n the msg in test is: %s", *msg);

strcpy(*msg, "test");
printf("\nthe msg in test after is: %s\n", *msg);

change(&msg);
free(*msg);
}

int main(int argc, char** argv) {

char * msg;
test(&msg);
printf("\nthe msg back in main is: %s", msg);
}

我可以说它工作正常,但是你能告诉我何时以及如何需要释放分配的内存吗?因为如果我从函数更改和第三个中删除//并运行它,我会遇到错误。有没有办法在每个函数的第一个打印语句中获取消息的内容 - 请参阅 otuput:

the msg in test is: 
the msg in test after is: test
the msg in change is :0��
the msg in change after is: change
the msg in third is :P��
the msg in third after is: third
the msg back in main is:

有没有办法让消息发生变化:测试然后第三个消息是:更改

最佳答案

忘记那个程序吧,它有太多问题了:

  • 您不需要多层间接。两级就够了。如果该函数需要更改地址,只需将指针传递给下一个函数即可。
  • 您尝试在字符串初始化之前打印该字符串。
  • 您尝试在释放字符串后使用该字符串。
  • 通过重复调用 malloc 而不清理旧内容,会造成内存泄漏。请改用 realloc。
  • 您分配的内存量不正确,因此数组不够大,无法容纳您 strcpy 到其中的字符串。另请注意,您需要为空终止符分配足够的空间。

等等。这是一个固定版本:

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

void third(char** msg) {
const char str[] = "third";

*msg = realloc(*msg, sizeof(str));
printf("the msg in third is :%s\n", *msg);

strcpy(*msg, str);
printf("the msg in third after is: %s\n", *msg);
}

void change(char** msg) {
const char str[] = "change";

*msg = realloc(*msg, sizeof(str));
printf("the msg in change is :%s\n", *msg);

strcpy(*msg, str);
printf("the msg in change after is: %s\n", *msg);

third(msg);
}

void test(char** msg) {
const char str[] = "test";

*msg = malloc(sizeof(str));
printf("the msg in test is just garabage at this point, no need to print it.\n");

strcpy(*msg, str);
printf("the msg in test after is: %s\n", *msg);

change(msg);
}

int main(int argc, char** argv) {

char* msg;
test(&msg);
printf("the msg back in main is: %s\n", msg);

free(msg);
}

关于C char 数组、指针、malloc、free,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40890255/

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