#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *func(char * str){
int len;
len=strlen(str)+3;
str = (char *)realloc(str,len);
return str;
}
void main(){
printf("str:%s",func("hello"));
}
最后的 ans 打印 (null),而不是打印字符串:“hello”。谁能解释为什么会这样? 我无法识别任何错误。 任何人都可以纠正错误,并帮助我提供工作代码。请!
最佳答案
您的程序调用 undefined behavior因为您正在将一个指针传递给 realloc()
,而该指针以前未由动态内存分配器函数系列返回。
根据 C11
,章节 §7.22.3.5,realloc 函数,(强调我的)
If
ptr
is a null pointer, therealloc
function behaves like themalloc
function for the specified size. Otherwise, ifptr
does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to thefree
orrealloc
function, the behavior is undefined. [...]
也就是说,
对于托管环境,
void main()
至少应该是int main(void)
。Please see this discussion on why not to cast the return value of
malloc()
and family inC
. .
关于c - 为什么 realloc 在这种情况下不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38187701/