我的C代码在LOOP的第二次运行时打破了“realloc”函数

时间:2016-04-09 19:12:38

标签: c memory-management

它在这一行(在for循环中)中断了仅在程序的第二次运行中:  (arrP + i)=(char )realloc((* arrP + i),(sizeof(char)* currentLen));

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

int main(void)
{
    printf( "Please enter the amount of friends u have: \n\n \t" );
    unsigned int friendsNum = 0;
    scanf( "%d", &friendsNum );
    getchar();

    char** arrP = (char**)calloc( friendsNum, sizeof( char* ) );// pointer to a pointer array, that every item points on a str[0]
    unsigned int i = 0;
    unsigned int currentLen = 0;
    unsigned const int BUFFER = 28; // The maximum length you expect
    for (i = 0; i < friendsNum; i++)
    {
        *(arrP + i) = (char*)calloc( BUFFER, sizeof( char ) );
        if (!(arrP + i))
        {
            printf( "ERROR, EXITING" );
            return(1);
        }
        fgets( *(arrP + i), 20, stdin );
        (*(arrP + i))[strcspn( *(arrP + i), "\n" )] = '\0';
        currentLen = strlen( *(arrP + i) ) + 1;// including \0(+1)
        *(arrP + i) = (char*)realloc( (*arrP + i) ,  (sizeof( char ) * currentLen));
        if (!(arrP + i))
        {
            printf( "ERROR, EXITING" );
            return(1);
        }
    }


    getchar();  
    return 0;
}

1 个答案:

答案 0 :(得分:0)

问题在于*(arrP + i)(*arrP + i)不同:

  • 第一个表达式相当于arrP[i]
  • 第二个表达式相当于arrP[0]+i

如果您使用[]运算符而不是指针算术切换到基于下标的访问,您将拥有更轻松的代码:

arrP[i] = realloc(arrP[i], currentLen);

请注意,您不会在C中投射malloc,并且您可以依赖标准要求sizeof(char)1的事实。