我应该执行realloc的检查,如果新的块大小比初始小? [英] Should I enforce realloc check if the new block size is smaller than the initial?

查看:181
本文介绍了我应该执行realloc的检查,如果新的块大小比初始小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能的realloc在这种情况下会失败呢?

 为int *一个= NULL;A =释放calloc(100的sizeof(* a)条);
的printf(1.ptr数:%d \\ n,一);A = realloc的(一,50 *的sizeof(* a)条);
的printf(2.ptr数:%d \\ n,一);如果(A == NULL){
    的printf(是否有可能\\ n吗?);
}返回(0);

}

在我的情况的输出是:

  1.ptr:4072560
2.ptr:4072560

所以,一指向同一个地址。
所以我应该执行realloc的检查?

后来修改


  • 在Windows XP中使用MinGW的编译器。

  • 是在Linux上的gcc类似的行为?

后来修改 2:
是否确定要检查这种方式?

 为int * A = NULL,* B = NULL;A =释放calloc(100的sizeof(* a)条);
B = realloc的(一,50 *的sizeof(* a)条);如果(二== NULL){
    返回;
}
A = B;
返回;


解决方案

是的,你应该总是强制执行realloc的支票,或与此有关的任何其他内存分配。

重复使用同一地址的当前行为是不应该依赖该等资料的实现细节。这样做是刚刚开放和自己的错误时,无论是库开关它的实现,或者你移动到一个新的平台。

时很可能这将永远失败?或许不会,我会很惊讶,如果你能找到它的情况。然而,这并不意味着它不会。在功能,会自动检查每个操作包裹的realloc非常简单,没有理由不这样做。

 无效* xrealloc(无效* PTR,为size_t大小){
  PTR =的realloc(PTR,大小);
  如果(!PTR){
    出口(EXIT_FAILURE);
  }
  返回PTR;
}

Can realloc fail in this case?

int *a = NULL;

a = calloc(100, sizeof(*a));
printf("1.ptr: %d\n", a);

a = realloc(a, 50 * sizeof(*a));
printf("2.ptr: %d\n", a);

if(a == NULL){
    printf("Is it possible?\n");
}

return (0);

}

The output in my case is:

1.ptr: 4072560
2.ptr: 4072560

So 'a' points to the same adress. So should I enforce realloc check?

Later edit:

  • Using MinGW compiler under Windows XP.
  • Is the behaviour similar with gcc on Linux ?

Later edit 2: Is it OK to check this way ?

int *a = NULL, *b = NULL;

a = calloc(100, sizeof(*a));
b = realloc(a, 50 * sizeof(*a));

if(b == NULL){
    return a;
}
a = b;
return a;

解决方案

Yes, you should always enforce a check on realloc, or any other memory allocation for that matter.

The current behavior of re-using the same address is an implementation detail that should not be relied upon. Doing so is just opening yourself up for bugs when either the library switches it's implementation or you move to a new platform.

Is it likely this will ever fail? Probably not, I'd be astounded if you could find a case that it does. However that doesn't mean it won't. Wrapping realloc in a function which automatically does the check for every operation is simple enough that there's no reason to not do it.

void* xrealloc(void* ptr, size_t size) {
  ptr = realloc(ptr, size);
  if ( !ptr ) {
    exit(EXIT_FAILURE);
  }
  return ptr;
}

这篇关于我应该执行realloc的检查,如果新的块大小比初始小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆