当我们用负参数调用Malloc时会发生什么? [英] what happens when we call Malloc with negative parameter?

查看:832
本文介绍了当我们用负参数调用Malloc时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

7.22.3.4 malloc函数malloc函数为一个对象分配空间,该对象的大小由size指定,其值是 不确定.

7.22.3.4 The malloc function The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.

原型:void *malloc(size_t size);

我尝试将负值作为参数传递:malloc(negative)返回NULL.

I tried passing a negative value as a parameter: malloc(negative) returns NULL.

是因为[size_t]负数转换为无符号的[某个大值],并且无法分配所需的空间,还是函数检查参数返回了NULL?

Is it because the [size_t] negative converted to unsigned [some big value] and cannot allot required space or is the function checking parameter and returns NULL?

如果将其转换为大正值,则在调用malloc(INT_MIN+2)时仍返回NULL,但是分配给指针的malloc(0)*p = somevalue起作用.那怎么办?

If its getting converted to big positive, then when calling malloc(INT_MIN+2) it still returns NULL, but malloc(0) alloted to pointer and *p = somevalue works. What about this?

实现定义了吗?

阅读此链接: malloc(0)

推荐答案

即使您将负值传递给mallocsize_t值也始终为正.负值将转换为类型为size_t的无符号值,这将导致巨大的正值.

A size_t value is always positive even if you pass a negative value to malloc. The negative value is converted to an unsigned value of type size_t which leads to a huge positive value.

示例:

char *p = malloc(-2);

等效于:

char *p = malloc(SIZE_MAX - 1);  // SIZE_MAX is the maximum
                                 // size_t value 

这篇关于当我们用负参数调用Malloc时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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