Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Whats wrong with casting mallocs return value?

casting malloc Return value wrong
0
Posted

Whats wrong with casting mallocs return value?

0

Suppose that you call malloc but forget to #include . The compiler is likely to assume that malloc is a function returning int, which is of course incorrect, and will lead to trouble. Now, if your call to malloc is of the form char *p = malloc(10); the compiler will notice that you’re seemingly assigning an integer to a pointer, and will likely emit a warning of the form “assignment of pointer from integer lacks a cast” (see question 7.6), which will alert you to the problem. (The problem is of course that you forgot to #include , not that you forgot to use a cast.) If, on the other hand, your call to malloc includes a cast: char *p = (char *)malloc(10); the compiler is likely to assume that you know what you’re doing, that you really do want to convert the int returned by malloc to a pointer, and the compiler therefore probably won’t warn you. But of course malloc does not return an int, so trying to convert the int that it doesn’t return to a pointer is likely t

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123