c - 为什么 realloc 在这种情况下不能正常工作?

标签 c string pointers realloc

#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, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined. [...]

也就是说,

关于c - 为什么 realloc 在这种情况下不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38187701/

相关文章:

c - 从 char 缓冲区读取一位

c - 这是 C 标准中整数类型符号位定义的错误吗?

c - 理解 C 中的函数原型(prototype)

python - 用字符切片 numpy 数组

python - 在python中保存x,y坐标

python - 使用 Python 在不同实例中分割 verilog 路径的正则表达式模式

c - 读取每行 3 个字符的文件时,sizeof(char) 不起作用

代码在 Windows 中有效,但在 Linux 中无效!为什么? 【简单的指针问题】

c - 如何按值发送数组以在c中运行?

c - malloc 和 realloc 段错误