在的malloc函数 - 分段错误 [英] malloc in function — segmentation error

查看:136
本文介绍了在的malloc函数 - 分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本程序完美的作品:

#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 部分。当我这样做,我得到一个分段错误。

But for future convenience I would like to put the malloc section inside the tempfunction. When I do that, I get a segmentation fault error.

我想这可能是由于初始化这样的,而不是的char **意见; 我写的:

I thought it might be due to initialization, so instead of char **comments; I write:

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

但是,它仍然无法正常工作。我会很感激,如果你能帮助我理解为什么会这样,以及如何解决它。

But, it still doesn't work. I would be very grateful if you could help me understand why this happens and how to fix it.

推荐答案

尝试:

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

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

Of course you'll have to free at the end in order to avoid memory leaks

这篇关于在的malloc函数 - 分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆