c语言中malloc如何声明,问下关于malloc的声明问题

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

Advantages to casting

Including the cast allows a program or function to compile as C++.

The cast allows for pre-1989 versions of malloc that originally returned a char *.[8]

Casting can help the developer identify inconsistencies in type sizing should the destination pointer type change, particularly if the pointer is declared far from the malloc() call.[edit]Disadvantages to casting

Under the ANSI C standard, the cast is redundant.

Adding the cast may mask failure to include the header stdlib.h, in which the prototype for malloc is found.[8][9] In the absence of a prototype for malloc, the standard requires that the C compiler assumemalloc returns an int. If there is no cast, a warning is issued when this integer is assigned to the pointer; however, with the cast, this warning is not produced, hiding a bug. On certain architectures and data models (such as LP64 on 64-bit systems, where long and pointers are 64-bit and int is 32-bit), this error can actually result in undefined behaviour, as the implicitly declared malloc 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 they uniformly produce warnings that an undeclared function has been used, so a warning will still appear. For example, GCC's default behaviour is to show a warning that reads "incompatible implicit declaration of built-in function" regardless of whether the cast is present or not.

If the type of the pointer is changed, one must fix all code lines where malloc was called and cast (unless it was cast to a typedef).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值