64 位 iOS 设备中的 realloc()

realloc() in a 64bit iOS device

当我在项目中使用 C 函数 realloc(p,size) 时,代码在模拟器和 iPhone 5.

上都运行良好

但是,当 iPhone 6 plus 上的代码为 运行 时,会发生一些奇怪的事情。 a指向的内容已更改!更糟糕的是,每次函数运行的输出都不一样!

这里是测试代码:

#define LENGTH (16)

- (void)viewDidLoad {

    [super viewDidLoad];   

    char* a = (char*)malloc(LENGTH+1);  
    a[0] = 33;

    a[1] = -14;

    a[2] = 76;

    a[3] = -128;

    a[4] = 25;

    a[5] = 49;

    a[6] = -45;

    a[7] = 56;

    a[8] = -36;

    a[9] = 56;

    a[10] = 125;

    a[11] = 44;

    a[12] = 26;

    a[13] = 79;

    a[14] = 29;

    a[15] = 66;

    //print binary contents pointed by a, print each char in int can also see the differene

    [self printInByte:a];

    realloc(a, LENGTH);

    [self printInByte:a]



    free(a);

}

-(void) printInByte: (char*)t{

    for(int i = 0;i < LENGTH ;++i){

        for(int j = -1;j < 16;(t[i] >> ++j)& 1?printf("1"):printf("0"));

        printf(" ");

        if (i % 4 == 3) {

            printf("\n");

        }

    }

}

还有一件事,当 LENGTH 不是 16 时,它可以很好地分配到 [LENGTH-1]。但是,如果 LENGTH 恰好是 16,就会出错。

任何想法将不胜感激。

您需要做的:

a = realloc(a, LENGTH);

原因是realloc()可能会移动块,所以你需要更新你的指针到新地址:

http://www.cplusplus.com/reference/cstdlib/realloc/

来自 realloc man 文档:

The realloc() function tries to change the size of the allocation pointed to by ptr to size, and returns ptr. If there is not enough room to enlarge the memory allocation pointed to by ptr, realloc() creates a new allocation, copies as much of the old data pointed to by ptr as will fit to the new allocation, frees the old allocation, and returns a pointer to the allocated memory.

所以,你必须这样写:a = realloc(a, LENGTH);因为在已经分配的内存块不能变大的情况下,该区域将被移动到另一个位置,因此,该区域的地址会改变。这就是为什么 realloc return 内存指针。