C:将较小的内存部分复制到较大的部分而不知道较小的部分,如realloc()

时间:2013-10-02 09:33:26

标签: memory memory-management memcpy realloc

realloc函数(c)如何只占用内存的 new 部分的长度,复制(更小,以强制出现问题)内存部分到一个? (假设它需要,就像在内存中找不到与块相邻的内存来扩展它)

如果它从较小的部分调整了完整大小(第二个arg到realloc),它将从无效的内存中读取,对吧?

谢谢, Ĵ

编辑:代表一个极端例子的代码:

int main ( void ) {
  unsigned int i=0;
  void *test_ptr1, *test_ptr2;

  // this first bit just finds the size of the available heap, ignore it if you wish
  do {
    free(test_ptr1); 
    printf("%u\n",i);
    i+=1073741824; // 1GiB
  } while ((test_ptr1 = malloc(i)));
  i-=1073741824;
  do {
    free(test_ptr1); 
    printf("%u\n",i);
    i+=1048576; // 1MiB
  } while ((test_ptr1 = malloc(i)));
  i-=1048576;
  do {
    free(test_ptr1); 
     printf("%u\n",i);
     i+=1024; // 1KiB
  } while ((test_ptr1 = malloc(i)));
  i-=1024;
  do {
    free(test_ptr1);
    printf("%u\n",i); 
    i+=128; // 128B
  } while ((test_ptr1 = malloc(i)));
  i-=128;
  do {
    free(test_ptr1);
    printf("%u\n",i); 
    i++; // 1B
  } while ((test_ptr1 = malloc(i)));
  i--;

  // i is now equal to the size of the available heap (I think...)

  test_ptr1 = calloc(i-1, 1); // calloc all but one byte of the available heap
  test_ptr2 = malloc(1); // malloc the reamining byte
  printf("proving calloc: %u\n", ((char *)test_ptr1)[i-2]); // outputs 0, this might be a point of weakness int this program, if this is optimised in any way it fails to demonstrate the effect
  *(char *)test_ptr2 = 'c'; // initialise the byte to 'c'
  free(test_ptr1); // free the vast majority of the heap
  if ((test_ptr1 = realloc(test_ptr2, i-1))) { // realloc the one byte to the space taken up by the previous calloc that was freed in the previous line
    printf("realloc success: %c\n", *(char *)test_ptr1); // outputs c, but whats in the rest of this memory section? and more informatively, where was it coppied from?
    getc(stdin);
    free(test_ptr1);
    free(test_ptr2);
    return 0; 
  } else {
    printf("realloc failed\n");
    free(test_ptr2);
    return -1;
  }
}

输出:

1945305043
1945305044
1945305045
1945305046
1945305047
1945305048
1945305049
1945305050
1945305051
1945305052
1945305053
1945305054
1945305055
1945305056
proving calloc: 0
realloc success: c

2 个答案:

答案 0 :(得分:1)

  

如果它从中填充了完整大小(第二个arg到realloc)   较小的部分,它会从无效的内存中读取,对吗?

你是对的,看一下文档:

  

内存块的内容保留到较小的内容   新旧尺寸,即使块移动到新位置。 如果   新大小越大,新分配的值就越大   不确定的。

答案 1 :(得分:1)

如果有其他人想知道这个问题的答案你可能会对这个链接感兴趣:http://bytes.com/topic/c/answers/600170-implementing-realloc它非常有用,但读完整个事情b / c第一个有一些不好的信息几个帖子。