malloc in function – 分割错误

这个程序完美地运作:

#include  #include  #include  #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); 

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

如果要更改函数内的comments ,则必须传递它的地址,以使其适当反映。 所以你需要传递&commentschar ***tempfunction()

我建议将代码更新为:

 int tempfunction (char ***ref_comments) { char str1[]="First string\n"; char str2[]="This is the second string\n"; char **comments = malloc(MAX_NUM*sizeof(char *)); *(comments+0)=(char *) malloc(strlen(str1)+1); *(comments+1)=(char *) malloc(strlen(str2)+1); strcpy(*(comments+0), str1); strcpy(*(comments+1), str2); //now update the passed variable *nef_comments = comments; 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............................. */ // pass address of comments tempfunction(&comments); printf("%s%s", comments[0], comments[1]); return 0; } 

不要从main函数传递char **注释,而不是这样做,你可以在tempfunction中声明char **注释然后将注释的引用返回给main函数。 它会工作。