• realloc 用法


    #include <stdio.h> 
    #include <stdlib.h> 
    #include <string> 
      
    int main() 
    { 
        char * p_char; 
      
        //you should include <stdlib.h> - because that is where malloc() is declared 
        p_char=(char *)malloc(100); 
      
        int count(123456); 
        count=count<<10; 
        printf("count=%d",count); 
        //任务管理看到内存不断增大 
        //while(count>0) 
        //{ 
        //  p_char=(char *)malloc(100); 
        //  count--; 
        //} 
          
        //#include <string>  char * strcpy ( char * destination, const char * source ); 
        strcpy(p_char,"Hello"); 
        if(p_char) 
            //you should include <stdio.h> 
            printf("Memory allocated at %x
    ",p_char); 
        else
            printf("Not Enough Memory!
    "); 
      
        char * p_char_next; 
        p_char_next=p_char; 
      
        p_char=(char *)realloc(p_char,3); 
      
        //任务管理看到内存没有变化 
        while(count>0) 
        { 
            p_char=(char *)realloc(p_char,300); 
            count--; 
        } 
      
        if(p_char) 
            printf("Memory Reallocated at %x
    ",p_char); 
        else
            printf("Not Enough Memory!
    "); 
      
        printf("Source Address at %x
    ",p_char_next); 
        //printf("Content Of Source is %s,
    Content Of Current is %s
    ",*p_char,*p_char_next); 
      
        free(p_char); 
        getchar(); 
        return 0; 
    }; 
    realloc
    原型:extern void *realloc(void *mem_address, unsigned int newsize);
    用法:#include <stdlib.h> 有些编译器需要#include <alloc.h>
    功能:改变mem_address所指内存区域的大小为newsize长度。
    说明:如果重新分配成功则返回指向被分配内存的指针,否则返回空指针NULL。
    当内存不再使用时,应使用free()函数将内存块释放。
    详细说明及注意要点:
    1、如果有足够空间用于扩大mem_address指向的内存块,则分配额外内存,并返回mem_address
    这里说的是“扩大”,我们知道,realloc是从堆上分配内存的,当扩大一块内存空间时, realloc()试图直接从堆上现存的数据后面的那些字节中获得附加的字节,如果能够满足,自然天下太平。也就是说,如果原先的内存大小后面还有足够的空闲空间用来分配,加上原来的空间大小= newsize。那么就ok。得到的是一块连续的内存。
    2、如果原先的内存大小后面没有足够的空闲空间用来分配,那么从堆中另外找一块newsize大小的内存。
    并把原来大小内存空间中的内容复制到newsize中。返回新的mem_address指针。
     
    //free(p_char_next);
    if(p_char_next!=NULL)
    printf("p_char_next = %x. ",p_char_next);
    Attention:You cann't free p_char_next again.
     
    1、 返回void * 指针,调用成功。
    2、 返回NULL,当需要扩展的大小(第二个参数)为0并且第一个参数不为NULL,此时原内存变成了“freed(游离)”的了。
    3、 返回NULL,当没有足够的空间可供扩展的时候,此时,原内存空间的大小维持不变。
  • 相关阅读:
    .net 关于路径的总结
    asp.net Base64加解密
    asp.net中的<% %>,<%= %>,<%# %><%$ %>的使用
    asp.net Swiper 轮播动画
    ASP.NET中Literal控件的使用方法(用于向网页中动态添加内容)
    asp.net 获取表单中控件的值
    rgb值转换成16进制
    关于background全解
    移动端的性能陷阱
    原生JS实现雪花特效
  • 原文地址:https://www.cnblogs.com/hongjiumu/p/3498369.html
Copyright © 2020-2023  润新知