应用程序在 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 中的所有数据都会丢失。不执行错误检查,因为如果堆耗尽,malloc
和 realloc
可能返回 NULL。
关于c - realloc 函数破坏了应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36522426/