zoukankan      html  css  js  c++  java
  • realloc函数

      原型:extern void *realloc(void *ptr, size_t newsize);
      用法:#include <stdlib.h>
      功能:改变ptr所指内存区域的大小为newsize长度。
      说明:如果重新分配成功则返回指向被分配内存的指针,否则返回空指针NULL。
            当内存不再使用时,应使用free()函数将内存块释放。

    #include <stdio.h>
    #include <stdlib.h>

    int main(int argc, char **argv)
    {

        char *p;
        p = (char *)malloc(100);
        if(p)
            printf("Memory Allocated at:%p\n", p);
        else
            printf("Not Enough Memory!\n");

        p = (char *)realloc(p, 256);

        if(p)
            printf("Memory Reallocated at:%p\n", p);
        else
            printf("Not Enough Memory!\n");


        free(p);

        return 0;
    }

    //==========================================================================
    通常,realloc的用法会如下:
    p = realloc(p, new_size);
    if (p == NULL) {
            return;
    }
    如果realloc()失败,ptr指向的这块内存不会变化,不会free或者移动。也就是说,如果realloc()失败了,照着上面代码的写法,这块内存就被永远遗忘了。
    tmp = realloc(p, new_size);
    if (tmp == NULL) {
            free(p);
            return;
    }
    p = tmp;



  • 相关阅读:
    Task示例,多线程
    request
    do put in ruby
    Ruby零星笔记
    Git的常用操作
    如何在Rails中执行Get/Post/Put请求
    Lua中的基本函数库
    Step By Step(Lua目录)
    position:fixed失效原因
    前端性能监控-window.performance.timing篇
  • 原文地址:https://www.cnblogs.com/liulipeng/p/2706970.html
Copyright © 2011-2022 走看看