Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
C dynamic memory allocation
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Disadvantages to casting=== * Under the C standard, the cast is redundant. * Adding the cast may mask failure to include the header <code>stdlib.h</code>, in which the [[function prototype]] for <code>malloc</code> is found.<ref name="Cprog_malloc" /><ref>{{cite web |url=http://www.c-faq.com/malloc/mallocnocast.html |title=comp.lang.c FAQ list Β· Question 7.7b |publisher=C-FAQ |access-date=9 March 2007 }}</ref> In the absence of a prototype for <code>malloc</code>, the C90 standard requires that the C compiler assume <code>malloc</code> returns an <code>int</code>. If there is no cast, C90 requires a diagnostic when this integer is assigned to the pointer; however, with the cast, this diagnostic would not be produced, hiding a bug. On certain architectures and data models (such as LP64 on 64-bit systems, where <code>long</code> and pointers are 64-bit and <code>int</code> is 32-bit), this error can actually result in undefined behaviour, as the implicitly declared <code>malloc</code> returns a 32-bit value whereas the actually defined function returns a 64-bit value. Depending on calling conventions and memory layout, this may result in [[stack smashing]]. This issue is less likely to go unnoticed in modern compilers, as C99 does not permit implicit declarations, so the compiler must produce a diagnostic even if it does assume <code>int</code> return. * If the type of the pointer is changed at its declaration, one may also need to change all lines where <code>malloc</code> is called and cast.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)