C - 函数内部的动态分配/重新分配

时间:2013-10-22 19:43:26

标签: c function segmentation-fault malloc realloc

我已经在C中编写了这个函数(函数应该接收char*,分配必要的空间,并在给定指针指向指针后面的字符索引的情况下插入字符)

void add_to_str(char *character, char ** string, int* index)
{
    //we dont expect  *string to be NULL !! no condition done
    if (*index == 0)    //if str is empty we will alloc AVGLEN(32) characters space
       *string=malloc(AVGLEN*sizeof(char));

    if (*string == NULL)   //malloc fails?
    {
        fprintf(stderr,errors[MALLOC]);
        exit(99);
    }
    //string length exceeds 32 characters we will allocate more space
    if ( *index > (AVGLEN-1) || character== NULL )// or string buffering ended, we will free redundant space
    {
        *string=realloc(*string,sizeof(char)*((*index)+2));//+1 == '\0' & +1 bcs we index from 0
        if (*string==NULL)   //realloc fails?
        {
            fprintf(stderr,errors[REALLOC]);
            exit(99);
        }
    }
    *string[(*index)++]=*character;
}

*index > 0时,它会在行上显示分段错误

*string[(*index)++]=*character;

此功能的一个变体(malloc后面只有char*,然后将字符分配给string[i++])完美无缺。

3 个答案:

答案 0 :(得分:3)

你必须小心这句话:

*string[(*index)++]=*character;

因为数组索引的优先级高于指针解除引用的优先级。因此,这与

相同
*(string[(*index)++]) = *character;

这不是你想要的。你想要这个:

(*string)[(*index)++] = *character;

错误代码适用于*index == 0,因为在这种情况下,该语句等同于**string,该语句仍然有效,但在index > 0时,string将会是在无效位置取消引用:string+index

答案 1 :(得分:0)

请注意,执行以下操作:

ptr = realloc(ptr, ...);

是一个非常糟糕的模式。当realloc()失败时,您的旧分配区域将无法再被程序访问并被泄露。正确的模式是:

char* str_new = realloc(string, ...);

if (str_new != NULL)
    string = str_new;
else
    /* handle allocation error */

答案 2 :(得分:0)

首先,函数fprintf需要格式字符串。

即。

 fprintf(stderr,errors[MALLOC]);

可能无效。

此功能的目的是什么?似乎没有叙述,