为什么书中说,我必须投的malloc? [英] Why does the book say I must cast malloc?

查看:113
本文介绍了为什么书中说,我必须投的malloc?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我达到了页面的 167 C编程语言(第二版布赖恩W. Kernighan的&放;丹尼斯·里奇先生),发现作者说,我必须投的malloc 。下面是部分从书:


  

7.8.5存储管理


  
  

函数malloc和释放calloc获得的内存块动态。

 的void * malloc的(为size_t N)


  
  

返回一个指向未初始化的存储,或NULL的n个字节,如果要求不能得到满足。

 无效*释放calloc(为size_t N,为size_t大小)


  
  

返回一个指向足够的自由空间为指定大小的n个对象的数组,或NULL,如果
      要求不能得到满足。存储被初始化为零。
      由malloc或calloc返回的指针有问题的对象适当的调整,
      但它必须被转换成适当的类型,如

 为int *的IP;
IP =(INT *)释放calloc(N,的sizeof(INT));


我已经知道的malloc (及其家庭)返回一个类型的无效* 也有很好的解释为什么不投的malloc

不过,我的问题是:为什么这本书说我应该投它


解决方案

从<一个href=\"http://computer-programming-forum.com/47-c-language/a9c4a586c7dcd3fe.htm\">http://computer-programming-forum.com/47-c-language/a9c4a586c7dcd3fe.htm:


  

在pre-ANSI C - 如K&放描述; R-1 - malloc()函数返回一个的char *
  因此有必要在所有情况下施展它的返回值,其中
  接收变量是不是也是一个的char * 。新的无效* 键入
  标准C使得这些扭曲是不必要的。


  
  

要拯救任何人不必要地跳跃到的尴尬
  K&安培的防御; R-2,我问丹尼斯里奇征求意见,我可以
  在判决的有效性引自第142页。他上面引用
  回答:


  
  

    

在任何情况下,现在我重读页上的东西。 142,我认为这是
        错误;这是写的,因为它不只是防守这样的方式
        与早期的规则,它misre presents的ANSI规则。


  

Today I reached page 167 of The C Programming Language (second edition Brian W. Kernighan & Dennis M. Ritchie) and found that the author says I must cast malloc. Here is the part from the book:

7.8.5 Storage Management

The functions malloc and calloc obtain blocks of memory dynamically.

void *malloc(size_t n)

returns a pointer to n bytes of uninitialized storage, or NULL if the request cannot be satisfied.

void *calloc(size_t n, size_t size)

returns a pointer to enough free space for an array of n objects of the specified size, or NULL if the request cannot be satisfied. The storage is initialized to zero. The pointer returned by malloc or calloc has the proper alignment for the object in question, but it must be cast into the appropriate type, as in

int *ip;
ip = (int *) calloc(n, sizeof(int));

I already know that malloc (and its family) returns type void*, and there are good explanations why not to cast malloc.

But my question is: Why does the book say I should cast it?

解决方案

From http://computer-programming-forum.com/47-c-language/a9c4a586c7dcd3fe.htm:

In pre-ANSI C -- as described in K&R-1 -- malloc() returned a char * and it was necessary to cast its return value in all cases where the receiving variable was not also a char *. The new void * type in Standard C makes these contortions unnecessary.

To save anybody from the embarrassment of leaping needlessly to the defence of K&R-2, I asked Dennis Ritchie for an opinion that I could quote on the validity of the sentence cited above from page 142. He replied:

In any case, now that I reread the stuff on p. 142, I think it's wrong; it's written in such a way that it's not just defensive against earlier rules, it misrepresents the ANSI rules.

这篇关于为什么书中说,我必须投的malloc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆