what happens when we call Malloc with negative parameter?

夙愿已清 提交于 2020-01-20 03:54:04

问题


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.

Prototype: void *malloc(size_t size);

I tried passing a negative value as a parameter: malloc(negative) returns 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?

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?

Is it implementation defined?

Read this link:malloc(0)


回答1:


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.

Example:

char *p = malloc(-2);

is equivalent to:

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



回答2:


Since the argument to malloc is of type size_t which is unsigned but you are passing an integer which is signed, the integer value will be converted to size_t the rules for this are covered in the draft C99 standard section 6.3.1.3 Signed and unsigned integers which comes under Conversions and it says:

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.49)

Let's look at an example of what this means, if you pass in -1 then max size_t value + 1 will be added:

-1 + MAX_SIZE_T + 1

which results in:

 MAX_SIZE_T

For -5 you would end up with:

MAX_SIZE_T - 4

This means for small negative values the resulting size_t value will be a very large positive number.

So why do you receive NULL back for malloc in these cases? If we go back to the the draft standard section 7.20.3 Memory management functions it says:

If the space cannot be allocated, a null pointer is returned

You are making a request that is too large and the space can not be allocated.



来源:https://stackoverflow.com/questions/17925771/what-happens-when-we-call-malloc-with-negative-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!