zoukankan      html  css  js  c++  java
  • C语言stdlib库中的malloc和realloc

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    //void *malloc(size_t size) 
    //分配所需的内存空间,并返回一个指向它的指针。若失败,则返回NULL
    
    //char* strcpy(char* dest, const char* src) 
    //把 src 所指向的字符串复制到 dest。
    //如果目标数组 dest 不够大,而源字符串 src 的长度又太长,可能会造成缓冲溢出的情况。
    
    //char *strcat(char *dest, const char *src) 
    //把 src 所指向的字符串追加到 dest 所指向的字符串的结尾。
    
    //void* realloc(void* ptr, size_t size) 
    //尝试重新调整之前调用 malloc 或 calloc 所分配的 ptr 所指向的内存块的大小。
    
    
    int main()
    {
        //分配内存
        char* str = (char*)malloc(10);
        strcpy(str, "hello malloc");
        printf("str = %s,  address = %u
    ", str, str);
    
        //重新分配内存
        str = (char*)realloc(str, 25);
        strcat(str, " realloc");
        printf("str = %s,  address = %u
    ", str, str);
        free(str);
    
        return(0);
    }
    

    程序输出:

    str = hello malloc,  address = 7953136
    str = hello malloc realloc,  address = 7953136
    
  • 相关阅读:
    原始套接字-自定义IP首部和TCP首部
    原始套接字-TCP/IP下三层数据显示
    ARP欺骗分析
    博弈论
    C++ map & set
    selenium+chrome配置环境
    windows下安装python+selenium
    python之configParser模块读写配置文件
    接口测试流程
    Python之读取文件配置
  • 原文地址:https://www.cnblogs.com/liutongqing/p/13373082.html
Copyright © 2011-2022 走看看