码迷,mamicode.com
首页 > 其他好文 > 详细

malloc、calloc、realloc的区别

时间:2015-03-16 10:58:57      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:

http://blog.csdn.net/shuaishuai80/article/details/6140979

 

malloc、calloc、realloc的区别

分类: C Language

(1)C语言跟内存分配方式

<1>从静态存储区域分配.
       内存在程序编译的时候就已经分配好,这块内存在程序的整个运行期间都存在.例如全局变量、static变量.
<2>在栈上创建
       在执行函数时,函数内局部变量的存储单元都可以在栈上创建,函数执行结束时这些存储单元自动被释放.栈内存分配运算内置于处理器的指令集中,效率很高,但是分配的内存容量有限.

<3>从堆上分配,亦称动态内存分配.
       程序在运行的时候用malloc或new申请任意多少的内存,程序员自己负责在何时用free或delete释放内存.动态内存的生存期由用户决定,使用非常灵活,但问题也最多.


(2)C语言跟内存申请相关的函数主要有 alloca、calloc、malloc、free、realloc等.
    <1>alloca是向栈申请内存,因此无需释放.
    <2>malloc分配的内存是位于堆中的,并且没有初始化内存的内容,因此基本上malloc之后,调用函数memset来初始化这部分的内存空间.
    <3>calloc则将初始化这部分的内存,设置为0.
    <4>realloc则对malloc申请的内存进行大小的调整.
    <5>申请的内存最终需要通过函数free来释放.
    当程序运行过程中malloc了,但是没有free的话,会造成内存泄漏.一部分的内存没有被使用,但是由于没有free,因此系统认为这部分内存还在使用,造成不断的向系统申请内存,使得系统可用内存不断减少.但是内存泄漏仅仅指程序在运行时,程序退出时,OS将回收所有的资源.因此,适当的重起一下程序,有时候还是有点作用.
attention
    三个函数的申明分别是:
        void* malloc(unsigned size);
        void* realloc(void* ptr, unsigned newsize);  
        void* calloc(size_t numElements, size_t sizeOfElement); 
    都在stdlib.h函数库内,它们的返回值都是请求系统分配的地址,如果请求失败就返回NULL.
    (1)函数malloc()
        在内存的动态存储区中分配一块长度为size字节的连续区域,参数size为需要内存空间的长度,返回该区域的首地址.
    (2)函数calloc()
        与malloc相似,参数sizeOfElement为申请地址的单位元素长度,numElements为元素个数,即在内存中申请numElements*sizeOfElement字节大小的连续地址空间.
    (3)函数realloc()
        给一个已经分配了地址的指针重新分配空间,参数ptr为原有的空间地址,newsize是重新申请的地址长度.
    区别:
    (1)函数malloc不能初始化所分配的内存空间,而函数calloc能.如果由malloc()函数分配的内存空间原来没有被使用过,则其中的每一位可能都是0;反之, 如果这部分内存曾经被分配过,则其中可能遗留有各种各样的数据.也就是说,使用malloc()函数的程序开始时(内存空间还没有被重新分配)能正常进行,但经过一段时间(内存空间还已经被重新分配)可能会出现问题.
    (2)函数calloc() 会将所分配的内存空间中的每一位都初始化为零,也就是说,如果你是为字符类型或整数类型的元素分配内存,那么这些元素将保证会被初始化为0;如果你是为指针类型的元素分配内存,那么这些元素通常会被初始化为空指针;如果你为实型数据分配内存,则这些元素会被初始化为浮点型的零.
    (3)函数malloc向系统申请分配指定size个字节的内存空间.返回类型是 void*类型.void*表示未确定类型的指针.C,C++规定,void* 类型可以强制转换为任何其它类型的指针.
    (4)realloc可以对给定的指针所指的空间进行扩大或者缩小,无论是扩张或是缩小,原有内存的中内容将保持不变.当然,对于缩小,则被缩小的那一部分的内容会丢失.realloc并不保证调整后的内存空间和原来的内存空间保持同一内存地址.相反,realloc返回的指针很可能指向一个新的地址.
    (5)realloc是从堆上分配内存的.当扩大一块内存空间时,realloc()试图直接从堆上现存的数据后面的那些字节中获得附加的字节,如果能够满足,自然天下太平;如果数据后面的字节不够,问题就出来了,那么就使用堆上第一个有足够大小的自由块,现存的数据然后就被拷贝至新的位置,而老块则放回到堆上.这句话传递的一个重要的信息就是数据可能被移动.

[c-sharp] view plaincopy
 
  1.             #include <stdio.h>  
  2. #include <malloc.h>  
  3.   
  4. int main(int argc, char* argv[])   
  5. {   
  6.     char *p,*q;  
  7.     p = (char *)malloc(10);  
  8.     q = p;  
  9.     p = (char *)realloc(p,10);  
  10.     printf("p=0x%x/n",p);  
  11.     printf("q=0x%x/n",q);  
  12.       
  13.     return 0;   
  14. }   
  15.    输出结果:realloc后,内存地址不变  
  16.             p=0x431a70  
  17.             q=0x431a70  
  18.   
  19.    例2:  
  20.             #include <stdio.h>  
  21. #include <malloc.h>  
  22.   
  23. int main(int argc, char* argv[])   
  24. {   
  25.     char *p,*q;  
  26.     p = (char *)malloc(10);  
  27.     q = p;  
  28.     p = (char *)realloc(p,1000);  
  29.     printf("p=0x%x/n",p);  
  30.     printf("q=0x%x/n",q);  
  31.       
  32.     return 0;   
  33. }   
  34.    输出结果:realloc后,内存地址发生了变化  
  35.             p=0x351c0  
  36.             q=0x431a70  

 

http://zhidao.baidu.com/link?url=8lk5zuglYX4gkEfngqzG8lqgCL_IeX3CT0_Echr2qdwsO3MjkNv7kftSHSbCAjC6-IiASwqDJiIrWiaO4X6pUK

malloc的全称知道了但calloc的全称是啥?

2006-09-21 16:45moment616  分类:其他编程语言 | 浏览 1855 次  悬赏:10
如题...
MSDN上面好像也查不出来...
calloc
Allocates an array in memory with elements initialized to 0.
郁闷
malloc是memory allocation
我有更好的答案
 
 

1条回答

2014-07-31 19:49nwpujunesky | 四级 最快回答
The ‘c‘ indicates ‘cleared.‘ The allocated memory is initialised, or cleared. The initialisation value used by calloc is 0.
 
http://baike.baidu.com/link?url=teVLudn20nTwmEMfeAIXozherbo_K0kw6pHAJFpptbg5vM_Jg6KeutB4LaHfFr1BpNTm6514IzwtK7Bk5-b0uePfYY4IS8QOUFiOXrvhjJdLMSQtcFNos91sEHuBIls0fmHr3bvnOrL2Z3rVhOhz8_

malloc函数编辑malloc一般指malloc函数

malloc的全称是memory allocation,中文叫动态内存分配,当无法知道内存具体位置的时候,想要绑定真正的内存空间,就需要用到动态的分配内存。原型为extern void *malloc(unsigned int num_bytes)。
http://blog.csdn.net/firecityplans/article/details/4490124
 

malloc()与calloc区别

分类: c++

Both the malloc() and the calloc() functions are used to allocate dynamic memory. Each operates slightly different from the other.


Both the malloc() and the calloc() functions are used to allocate dynamic memory. Each operates slightly different from the other. malloc() takes a size and returns a pointer to a chunk of memory at least that big:
void *malloc( size_t size );
calloc() takes a number of elements, and the size of each, and returns a pointer to a chunk of memory 
at least big enough to hold them all:
void *calloc( size_t numElements, size_t sizeOfElement );
There are one major difference and one minor difference between the two functions. The major difference is that malloc() doesn‘t initialize the allocated memory. The first time malloc() gives you a particular chunk of memory, the memory might be full of zeros. If memory has been allocated, freed, and reallocated, it probably has whatever junk was left in it.
*****
 That means, unfortunately, that a program might run in simple cases (when memory is never reallocated) but break when used harder (and when memory is reused). 
*****
这句话说的意思看了2遍还是吃不透....
calloc() fills the allocated memory with all zero bits. That means that anything there you are going to use as a char or an int of any length, signed or unsigned, is guaranteed to be zero. Anything you are going to use as a pointer is set to all zero bits. 
That is usually a null pointer, but it is not guaranteed.Anything you are going to use as a float or double is set to all zero bits; that is a floating-point zero on some types of machines, but not on all. 
The minor difference between the two is that calloc() returns an array of objects; malloc() returns one object. Some people use calloc() to make clear that they want an array.

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/missuever/archive/2005/11/30/540045.aspx

 

另外说明:

 

1.分配内存空间函数malloc

  调用形式: (类型说明符*) malloc (size) 功能:在内存的动态存储区中分配一块长度为"size" 字节的连续区域。函数的返回值为该区域的首地址。 “类型说明符”表示把该区域用于何种数据类型。(类型说明符*)表示把返回值强制转换为该类型指针。“size”是一个无符号数。例如: pc=(char *) malloc (100); 表示分配100个字节的内存空间,并强制转换为字符数组类型, 函数的返回值为指向该字符数组的指针, 把该指针赋予指针变量pc。

2.分配内存空间函数 calloc

  calloc 也用于分配内存空间。调用形式: (类型说明符*)calloc(n,size) 功能:在内存动态存储区中分配n块长度为“size”字节的连续区域。函数的返回值为该区域的首地址。(类型说明符*)用于强制类型转换。calloc函数与malloc 函数的区别仅在于一次可以分配n块区域。例如: ps=(struet stu*) calloc(2,sizeof (struct stu)); 其中的sizeof(struct stu)是求stu的结构长度。因此该语句的意思是:按stu的长度分配2块连续区域,强制转换为stu类型,并把其首地址赋予指针变量ps。

 

简单的说是:

 

malloc它允许从空间内存池中分配内存,malloc()的参数是一个指定所需字节数的整数.
例如:P=(int*)malloc(n*sizeof(int));
  colloc与malloc类似,但是主要的区别是存储在已分配的内存空间中的值默认为0,使用malloc时,已分配的内存中可以是任意的值.
  colloc需要两个参数,第一个是需要分配内存的变量的个数,第二个是每个变量的大小.
例如:P=(int*)colloc(n,colloc(int));

 

另一个版本:

 

函数原型不同:
void *malloc(unsigned size)//动态申请size个字节的内存空间;功能:在内存的动态存储区中分配一块长度为" size" 字节的连续区域。函数的返回值为该区域的首地址。。(类型说明符*)表示把返回值强制转换为该类型指针。

(void *)calloc(unsigned n,unsigned size)//      用于向系统动态申请n个, 每个占size个字节的内存空间; 并把分配的内存全都初始化为零值。函数的返回值为该区域的首地址

(void *)realloc(void *p,unsigned size)//将指针p所指向的已分配内存区的大小改为size

区别:两者都是动态分配内存。主要的不同是malloc不初始化分配的内存,已分配的内存中可以是任意的值. calloc 初始化已分配的内存为0。次要的不同是calloc返回的是一个数组,而malloc返回的是一个对象。

malloc它允许从空间内存池中分配内存,          malloc()的参数是一个指定所需字节数的整数.
例如:P=(int*)malloc(n*sizeof(int));

colloc与malloc类似,    colloc需要两个参数,第一个是需要分配内存的变量的个数, 第二个是每个变量的大小.
例如:P=(int*)colloc(n,sizeof(int)); 

例,申请一个字符大小的指针
char *p=(char *)malloc(sizeof(char)); //当然单个是没有什么意义的申请动态数组或一个结构,如

char *str=(char *)malloc(sizeof(char)*100); //相当于静态字符数组str[100],但大小可以更改的

typedef struct pointer
{ int data; 
struct pointer *p; 
} pp; 

pp *p=(pp *)malloc(sizeof(struct pointer)); //动态申请结构体空间

其他几个函数是队申请空间的修改的操作根据定义自己可以试试

 

 

再一个版本:

http://nuomi1988.blog.hexun.com/35121805_d.html

一:它们都是动态分配内存,先看看它们的原型:

void *malloc( size_t size ); //分配的大小

void *calloc( size_t numElements, size_t sizeOfElement ); // 分配元素的个数和每个元素的大小

共同点就是:它们返回的是 void * 类型,也就是说如果我们要为int或者其他类型的数据分配空间必须显式强制转换;

不同点是:用malloc分配存储空间时,必须由我们计算需要的字节数。如果想要分配5个int型的空间,那就是说需要5*sizeof(int)的内存空间:

int * ip_a;
ip_a = (int*)malloc( sizeof (int) * 5 );

而用calloc就不需要这么计算了,直接:

ip_a = ( int* )calloc( 5, sizeof(int) );这样,就分配了相应的空间,而他们之间最大的区别就是:用malloc只分配空间不初始化,也就是依然保留着这段内存里的数据,而calloc则进行了初始化,calloc分配的空间全部初始化为0,这样就避免了可能的一些数据错误。

先写段代码体验体验....

#include <iostream>

using namespace std;

void main()
{
int * ip_a;
int * ip_b;


ip_a = (int*)malloc( sizeof (int) * 5 );
for( int i = 0; i < 5; i++ )
{
   cin>>ip_a[i];
}
for( int j = 0; j < 5; j++ )
{
   cout<<ip_a[j]<<" ";
}


ip_b = ( int* )calloc( 5, sizeof(int) );
for( int j = 0; j < 5; j++ )
{
   cout<<ip_b[j]<<" ";
}


}

这个输出就能够清晰的看出他们的不同....

 

 

++版:

三个函数的申明分别是:
void* realloc(void* ptr, unsigned newsize);
void* malloc(unsigned size);
void* calloc(size_t numElements, size_t sizeOfElement);
都在stdlib.h函数库内

它们的返回值都是请求系统分配的地址,如果请求失败就返回NULL

malloc用于申请一段新的地址,参数size为需要内存空间的长度,如:
char* p;
p=(char*)malloc(20);

calloc与malloc相似,参数sizeOfElement为申请地址的单位元素长度,numElements为元素个数,如:
char* p;
p=(char*)calloc(20,sizeof(char));
这个例子与上一个效果相同

realloc是给一个已经分配了地址的指针重新分配空间,参数ptr为原有的空间地址,newsize是重新申请的地址长度
如:
char* p;
p=(char*)malloc(sizeof(char)*20);
p=(char*)realloc(p,sizeof(char)*40);

注意,这里的空间长度都是以字节为单位。

C语言的标准内存分配函数:malloc,calloc,realloc,free等。
malloc与calloc的区别为1块与n块的区别:
malloc调用形式为(类型*)malloc(size):在内存的动态存储区中分配一块长度为“size”字节的连续区域,返回该区域的首地址。
calloc调用形式为(类型*)calloc(n,size):在内存的动态存储区中分配n块长度为“size”字节的连续区域,返回首地址。
realloc调用形式为(类型*)realloc(*ptr,size):将ptr内存大小增大到size。
free的调用形式为free(void*ptr):释放ptr所指向的一块内存空间。
C++中为new/delete函数。

http://stackoverflow.com/questions/5426700/c-if-realloc-is-used-is-free-necessary
 

When using realloc is the memory automatically freed? Or is it necessary to use free with realloc? Which of the following is correct?

//Situation A
ptr1 = realloc(ptr1, 3 * sizeof(int));

//Situation B
ptr1 = realloc(ptr2, 3 * sizeof(int));
free(ptr1);
ptr1 = ptr2;
shareimprove this question
 

5 Answers

Neither is correct. realloc() can return a pointer to newly allocated memory or NULL on error. What you should do is check the return value:

ptr1 = realloc(ptr2, 3 * sizeof(int));
if (!ptr1) {
    /* Do something here to handle the failure */
    /* ptr2 is still pointing to allocated memory, so you may need to free(ptr2) here */
}

/* Success! ptr1 is now pointing to allocated memory and ptr2 was deallocated already */
free(ptr1);
shareimprove this answer
 
1  
+1 for the only correct answer so far :) –  pmg Mar 24 ‘11 at 23:24
 

After ptr1 = realloc(ptr2, 3 * sizeof(int)); ptr2 is invalid and should not be used. You need to free ptr1 only. In some cases the return value of realloc will be the same value you passed in though.

You can safely consider ptr1=realloc(ptr2, ... as equivalent to this:

ptr1 = malloc(...);
memcpy(ptr1, ptr2, ...);
free(ptr2);

This is what happens in most cases, unless the new size still fits in the old memory block - then realloc could return the original memory block.

As other allocation functions, realloc returns NULL if it fails - you may want to check for that.

shareimprove this answer
 
1  
"ptr2 is invalid and should not be used" - unless a null pointer is returned, in which case ptr2 is still valid and still needs freeing eventually. So in the equivalent code, the second and third lines are both only if (ptr1).–  Steve Jessop Mar 24 ‘11 at 23:55

realloc() automatically frees the original memory, or returns it unchanged (aside from metadata) if you realloc() to a smaller size or there is unallocated memory available to simply expand the original allocation in place.

shareimprove this answer
 

In both situations, ptr1 must be freed.

Situation B is more complex because ptr2 potentially points to freed space. Or not. It depends on whether it could be reallocated. ptr2 should not be used after the realloc in B.

shareimprove this answer
 

According to http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/realloc returns the new memory block if the reallocation is successful, keeps the original memory block if not. Standard usage would look like this:

ptr2 = realloc(ptr1, new_size);
if (ptr2 == NULL) {
   //ptr1 still contains pointer to original array
} else {
   //ptr2 contains new array, ptr1 is invalid
}
shareimprove this answer
 
    
The description you provide is not in accordance with the behaviour the Standard mandates: reallocreturns NULL when it fails. –  pmg Mar 24 ‘11 at 23:24
    
I tried to fix it with the edit, didn‘t want to delete what was written. Do you know how to strikethrough the unwanted text here? –  Dadam Mar 24 ‘11 at 23:26 
1  
just remove the error. The point of editing is to improve the answer. If anyone thinks pmg‘s comment looks out of place in light of the answer as they see it, they can check the revision history. –  Steve Jessop Mar 24 ‘11 at 23:58

malloc、calloc、realloc的区别

标签:

原文地址:http://www.cnblogs.com/xuejinhui/p/4341229.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!