简体   繁体   中英

what happens when we call Malloc with negative parameter?

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)

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 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM