执行以下代码时会发生什么 [英] what will happen when following codes executed

查看:62
本文介绍了执行以下代码时会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int *a;
a=(int *)malloc(sizeof(int));

推荐答案

malloc语句首先查看堆上的可用内存量,并询问:是否有足够的可用内存来分配一个内存块要求的大小?"从传递给malloc的参数中可以知道该块所需的内存量-在这种情况下,sizeof(int)为4个字节.如果没有足够的可用内存,则malloc函数将返回地址零以指示错误(零的另一个名称为NULL,您将在整个C代码中使用该地址).否则malloc继续.

如果堆上有可用的内存,则系统会分配"或保留"指定大小的堆中的块.系统保留该内存块,以便不会被多个malloc语句意外使用.

然后,系统将保留块的地址放入指针变量(在这种情况下为p)中.指针变量本身包含一个地址.分配的块能够保存指定类型的值,并且指针指向该值.

参考: http://computer.howstuffworks.com/c29.htm [
The malloc statement first looks at the amount of memory available on the heap and asks, "Is there enough memory available to allocate a block of memory of the size requested?" The amount of memory needed for the block is known from the parameter passed into malloc -- in this case, sizeof(int) is 4 bytes. If there is not enough memory available, the malloc function returns the address zero to indicate the error (another name for zero is NULL and you will see it used throughout C code). Otherwise malloc proceeds.

If memory is available on the heap, the system "allocates" or "reserves" a block from the heap of the size specified. The system reserves the block of memory so that it isn''t accidentally used by more than one malloc statement.

The system then places into the pointer variable (p, in this case) the address of the reserved block. The pointer variable itself contains an address. The allocated block is able to hold a value of the type specified, and the pointer points to it.

Ref:http://computer.howstuffworks.com/c29.htm[^]


您应该阅读一本不错的C编程书.即使是偶然的C程序员也需要掌握内存分配,您不应该在Q& A中问这样一个基本的问题.
You should read a good C programming book. Mastering memory allocation is required even to the casual C programmer, you shouldn''t ask such a basic and fundamental question in the Q&A.


我将为*分配大小一个


这篇关于执行以下代码时会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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