c - 当指针有偏移量时,realloc 崩溃

标签 c arrays pointers realloc

我在下面有一个演示问题的简化 C 程序。当我尝试调用 realloc 时使用指针,它工作正常,但如果我尝试向指针添加偏移量(即从数组中的后面元素开始),它会失败。

# include <stdio.h>
# include <stdlib.h>

struct arbNum{
    unsigned char* bytes;
    long len;
};

void trim(struct arbNum* num){
    printf("%d,%d,%d,%d\n",num->bytes,num->bytes[0],num->bytes[1],num->len);
    unsigned char* nbytes = realloc(num->bytes,num->len);
    printf("Realloc successful.\n");
    num->bytes = nbytes;
}

int main(void){
    struct arbNum p = {calloc(2,1),2};
    trim(&p);
}

例如,这输出:
9247152,0,0,2
Realloc successful.

但是,从上面的代码,改变 realloc(num->bytes,num->len);realloc(num->bytes+1,num->len-1);将输出/行为更改为:
10361264,0,0,2

然后崩溃。可能我根本不了解指针,但我目前的理解是它们本质上是存储另一个值的地址。在这种情况下,为什么要提供 pointer+1不指向存储在比指针高一的地址中的值,或者换句话说,将充当该指针指向的数组的第一个元素的值。我想要做的是复制 num.bytes 指向的数组从第一个元素开始到内存中的新地址,但很明显,由于某种原因它失败了。

最佳答案

不,您只能realloc()在之前由 malloc() 返回的实际指针上或家人。

否则,它是 undefined behavior

报价C11 ,第 7.22.3.5 章

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. [....]



因此,您不能使用指针算术生成新地址,将其传递给 realloc()并期望重新分配部分,这是没有意义的。

关于c - 当指针有偏移量时,realloc 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47699683/

相关文章:

c - 使用 Lua 注册一个闭包

c - 系统()不起作用

c - "char s[static 10]"等函数的数组参数中 static 关键字的用途是什么?

javascript - 类似于 JavaScript 对象的合并/连接方法.. 不扩展

c++ - Boost find_first 它是如何工作的?/定义一个范围

c - 使用函数指针作为方法参数

java - 如何从嵌套数组中提取 JSON 数据?使用安卓

c - 如何将乘法运算符与指针一起使用?

c++ - 在 C++ 中通过引用将地址传递给类并从那里传递给它的 "child-class"

来自其他类的 C++ 成员函数指针