-4

While studying in detail about malloc() I came across this strange behavior.

int *p;
p=(int*)malloc(10.45);
p=(int*)malloc(10.45f);
p=(int*)malloc('j');

The program compiles with any of these statements with just a warning and returns a valid address. What's the real result here?

user2492165
  • 93
  • 1
  • 6

4 Answers4

5

All of those values are implicitly converted to size_t before calling the function, just as if you had an explicit cast. The floating point numbers are truncated, and the 'j' is interpreted as its numerical value in your character set.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
3

"Just a warning" probably hides the explanation.

Various rules for converting/promoting values of non-integer types to integer kick in, making sure malloc() gets a single size_t, i.e. an unsigned integer. The floating point calls will probably just drop the fractions for instance, and attempt to allocate 10 bytes.

Also, please don't cast the return value of malloc() in C.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
3

malloc() takes a size_t argument.

The compiler will truncate 10.45/10.45f to 10 and convert 'j' to its ASCII value (106).

It's an implicit cast to size_t

linkdd
  • 1,015
  • 1
  • 10
  • 24
  • No, it's rather an implicit conversion. A cast, by definition, is explicit. –  Sep 02 '13 at 14:56
2

Malloc is defined to accept an integer 'number of bytes'.

The C language defines the rules for converting from other data types to integers.

I'm sure you can work out for yourself what each value converts to.

bmargulies
  • 97,814
  • 39
  • 186
  • 310