如何在C中使用realloc
我试图使用realloc函数重新分配内存,我看到您以前需要使用malloc,但我不明白您是否必须使用它,因为假设我正在创建以下字符串:如何在C中使用realloc,c,realloc,C,Realloc,我试图使用realloc函数重新分配内存,我看到您以前需要使用malloc,但我不明白您是否必须使用它,因为假设我正在创建以下字符串: char string[] = "fun"; 如果我尝试添加更多空间,realloc函数会工作吗 这就引出了我的问题,我试图简单地在字符串的末尾添加一个字母,比如“p”,但由于某种原因,每次运行realloc行时,程序都会压碎realloc行 这是我的全部代码: int main() { char string[] = "fu
char string[] = "fun";
如果我尝试添加更多空间,realloc函数会工作吗
这就引出了我的问题,我试图简单地在字符串的末尾添加一个字母,比如“p”,但由于某种原因,每次运行realloc行时,程序都会压碎realloc行
这是我的全部代码:
int main()
{
char string[] = "fun" ;
str_func(string);
printf("%s", string);
return 0;
}
void str_func(char* str)
{
str = (char*)realloc(str, strlen(str) + 2);
strcat(str, "p");
}
我还尝试创建一个指向“string”的指针并发送该指针,结果是相同的。realloc函数只适用于最初使用一小组分配函数创建的对象(例如
malloc
、calloc
或realloc
本身)或空指针。因为string
不是这些东西,所以您的代码没有很好的定义
如果我尝试添加更多空间,realloc函数会工作吗
不,因为该数组没有在堆上分配-在您的例子中,它很可能是在堆栈上分配的,无法调整大小。简单地说:realloc
无法识别指针,也不知道如何处理它,但无论如何都会尝试执行某些操作,因此导致崩溃
只能对以前传递给malloc
的指针或空指针调用realloc
。这就是这些函数的工作原理
有关详细信息,请参阅
我以前看到你需要使用malloc,但我不明白你是否必须使用它
如果您需要使用malloc
才能realloc
某些东西,那么根据定义,您必须仅realloc
最初分配给malloc
的东西
你试图在“需要”和“必须”之间找到一些不存在的空间
。。。由于某种原因,该程序压碎了realloc
您已经说过您知道需要使用malloc
。然后您没有使用malloc
,您会问为什么这是一个问题。你至少可以尝试做你“知道”你需要做的事情,看看这是否能解决问题
这个程序应该看起来像
int main()
{
/* array is an automatic local variable. It wasn't dynamically allocated
in the first place, so can't be dynamically re-allocated either.
You cannot (and don't need to) free it either, it just goes out of scope
like any other automatic variable.
*/
char array[] = "fun";
/* you need to use malloc (or one of the other dynamic allocation functions)
before you can realloc, as you said yourself */
char *dynamic = malloc(1+strlen(array));
memcpy(dynamic, array, 1+strlen(array));
/* realloc can move your data, so you must use the returned address */
dynamic = str_func(dynamic);
printf("old:'%s', new:'%s'\n", array, dynamic);
/* not really essential since the program is about to exit anyway */
free(dynamic);
}
char* str_func(char* str)
{
char* newstr = realloc(str, strlen(str) + 2);
if (newstr) {
strcat(newstr, "p");
return newstr;
} else {
/* we failed to make str larger, but it is still there and should be freed */
return str;
}
}
您的原始条件不太正确:实际上指针传递给 。。。必须事先由
malloc()
、calloc()
或realloc()
分配,并且尚未通过调用free或realloc释放
[或]如果ptr为NULL,则行为与调用malloc(新大小)
相同
不,您只能使用
realloc()
从malloc()
或calloc()
(或从下面的realloc()
)或NULL
中获得的东西。所以您必须在之前使用malloc()?realloc(NULL,42)
是可以的,在这种情况下无需在之前使用malloc()
。是的。不要混合使用堆栈分配数组(普通数组)和堆分配数组(malloc
和realloc
)。这是否回答了您的问题?