gpt4 book ai didi

c - 函数中的 malloc — 段错误

转载 作者:太空宇宙 更新时间:2023-11-04 04:49:12 24 4
gpt4 key购买 nike

这个程序完美运行:

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

#define MAX_NUM 2

int tempfunction (char **comments)
{
char str1[]="First string\n";
char str2[]="This is the second string\n";

*(comments+0)=(char *) malloc(strlen(str1)+1);
*(comments+1)=(char *) malloc(strlen(str2)+1);

strcpy(*(comments+0), str1);
strcpy(*(comments+1), str2);
return 0;
}

int main(void)
{
char **comments;

/* This is the section I am talking about */
comments=(char **) malloc(MAX_NUM*sizeof(char *));
if (comments==NULL)
{
printf("\n### ERROR: malloc failed.\n");
exit(EXIT_FAILURE);
}
/* Upto here............................. */

tempfunction(comments);
printf("%s%s", comments[0], comments[1]);
return 0;
}

但为了将来方便,我想将 malloc 部分放在 tempfunction 中。当我这样做时,我得到一个段错误。

我认为这可能是由于初始化,所以我写的不是 char **comments;:

char a = 'a';
char *P = &a;
char **comments = &P;

但是,还是不行。如果您能帮助我理解为什么会发生这种情况以及如何解决它,我将不胜感激。

最佳答案

尝试:

int tempfunction (char ***comments)
{
char str1[]="First string\n";
char str2[]="This is the second string\n";

*comments = malloc(MAX_NUM * sizeof(**comments)); /* you must check the return of malloc */

(*comments)[0] = strdup(str1);
(*comments)[1] = strdup(str2);

return 0;
}

你这样调用它:

tempfunction(&comments);

当然你必须在最后释放以避免内存泄漏

关于c - 函数中的 malloc — 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17569992/

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