realloc功能打破了应用程序

时间:2016-04-09 20:39:22

标签: c memory-management realloc

应用程序打破了realloc功能,我不知道为什么......某人? 这是代码中断的行:         *(pointerToStr + i)= realloc(*(pointerToStr + i),sizeof(char)* lengthOfStr);

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

#define MAX_LEGIT_LENGTH 30
struct friend{
    unsigned const int stringLen;
    char* name;
}ori;
int main(void)
{
    unsigned int friendsNum = 0;
    unsigned int i = 0;
    unsigned int lengthOfStr = 0;
    char* pointerToStr = NULL;
    printf( "Please enter the amount of friends u have: \n\n \t" );
    scanf( "%d", &friendsNum );
    struct friend *friends = malloc( sizeof( struct friend ) * friendsNum );// struct array
    for (i = 0; i < friendsNum; i++)
    {

        (pointerToStr) = (char*)malloc( sizeof( char ) * MAX_LEGIT_LENGTH );
        printf( "Please enter the name of ur friend:\n" );
        getchar();
        fgets( (pointerToStr + i), 20, stdin );
        ((pointerToStr + i))[strcspn( (pointerToStr + i), "\n" )] = '\0';
        lengthOfStr = strlen( (pointerToStr + i) + 1 );
        *(pointerToStr + i) = realloc( *(pointerToStr + i), sizeof( char ) * lengthOfStr );
    }

1 个答案:

答案 0 :(得分:1)

*(pointerToStr + i),或更简洁,pointerToStr[i]不会返回malloc。因此,realloc不会接受它。块调整大小的正常方式是这样的

const size_t INITALLOC = 16;   /* #chars to alloc initially */
const size_t ALLOCSTEP =  8;   /* #chars to realloc by */

char *blk = malloc(INITALLOC);
size_t nalloced = INITALLOC;   /* #chars alloced */
size_t n = 0;                  /* #chars used */
size_t i;

for (i = 0; /* some condition */; ++i) {
    /* fill up the block */

    /* if array is full */
    if (n == nalloced)
        blk = realloc(blk, nalloced += ALLOCSTEP);
}

/* use blk */

/* return blk to the heap */
free(blk);

此处的问题是,如果realloc失败(返回NULL),则块中的所有数据都将丢失。不执行错误检查,因为如果堆耗尽,mallocrealloc可以返回NULL。

相关问题