c - realloc 函数破坏了应用程序

标签 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 );
    }

最佳答案

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

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),那么 block 中的所有数据都会丢失。不执行错误检查,因为如果堆耗尽,mallocrealloc 可能返回 NULL。

关于c - realloc 函数破坏了应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36522426/

相关文章:

c++ - C 程序终止

ios - UIWebView 在加载 PDF 文件时没有释放内存

memory-management - 重用变量但进程没有释放内存是否视为内存泄漏?

c - 如何在 C 中将 realloc 与双字符指针一起使用?

c - realloc bug - 增加数组的最后一个元素

C 中的 CGI : Page Redirect

c - 通过 typedef 传递和使用结构

c - 在 C 中的循环中分配和释放内存

c - 如何在 C 函数中返回 `realloc` 数组

c - 使用 __builtin_msa_ld_* 后如何转换为无符号 vector 类型