posts - 297,  comments - 15,  trackbacks - 0
首先看个问题程序:
#include <stdlib.h>
#include <stdio.h>
void main()
{
int *i;
i=(int *)malloc(sizeof(int));
*i=1;
*(i+1)=2;
printf(\"%x|%d\\n\",i,*i);
printf(\"%x|%d\",i+1,*(i+1));
}
输出的结果是:
8fc|1
8fe|2
这个程序编译通过,运行正常,说它有问题,问题出在哪呢?

首先通过malloc,建了一个大小为2的堆,
i指向的地址是8fc,i+1指向的地址是8fc+sizeof(int)=8fe
但是地址8fe是不受保护的,因为它不是机器分配给i+1的,随时会被其他变量占用。

正确的做法是
#include \"stdlib.h\"
#include \"stdio.h\"
void main()
{
int *i;
i=(int *)malloc(sizeof(int));
*i=1;
i=(int *)realloc(i,2*sizeof(int));
*(i+1)=2;
printf(\"%x|%d\\n\",i,*i);
printf(\"%x|%d\",i+1,*(i+1));
}
realloc 可以对给定的指针所指的空间进行扩大或者缩小,无论是扩张或是缩小,原有内存的中内容将保持不变。当然,对于缩小,则被缩小的那一部分的内容会丢失。 realloc 并不保证调整后的内存空间和原来的内存空间保持同一内存地址。相反,realloc 返回的指针很可能指向一个新的地址。
所以,在代码中,我们必须将realloc返回的值,重新赋值给 p :
p = (int *) realloc (p, sizeof(int) *15);

甚至,你可以传一个空指针(0)给 realloc ,则此时realloc 作用完全相当于malloc。
int* p = (int *) realloc (0,sizeof(int) * 10); //分配一个全新的内存空间,

这一行,作用完全等同于:
int* p = (int *) malloc(sizeof(int) * 10);

from:
http://blog.c114.net/html/07/206807-17133.html

posted on 2010-03-01 22:07 chatler 阅读(203) 评论(0)  编辑 收藏 引用 所属分类: C++_BASIS

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2009年3月>
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

常用链接

留言簿(10)

随笔分类(307)

随笔档案(297)

algorithm

Books_Free_Online

C++

database

Linux

Linux shell

linux socket

misce

  • cloudward
  • 感觉这个博客还是不错,虽然做的东西和我不大相关,觉得看看还是有好处的

network

OSS

  • Google Android
  • Android is a software stack for mobile devices that includes an operating system, middleware and key applications. This early look at the Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.
  • os161 file list

overall

搜索

  •  

最新评论

阅读排行榜

评论排行榜