[牛人杂谈] malloc()用法

[复制链接]
431|5
 楼主| antusheng 发表于 2022-6-11 20:07 | 显示全部楼层 |阅读模式
C 库函数 void *malloc(size_t size) 分配所需的内存空间,并返回一个指向它的指针。下面是 malloc() 函数的声明。

  1. void *malloc(size_t size)
参数
size -- 内存块的大小,以字节为单位。
返回值
该函数返回一个指针 ,指向已分配大小的内存。如果请求失败,则返回 NULL。


  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>

  4. int main()
  5. {
  6.    char *str;

  7.    /* 最初的内存分配 */
  8.    str = (char *) malloc(15);
  9.    strcpy(str, "21ic");
  10.    printf("String = %s,  Address = %u\n", str, str);

  11.    /* 重新分配内存 */
  12.    str = (char *) realloc(str, 25);
  13.    strcat(str, ".com");
  14.    printf("String = %s,  Address = %u\n", str, str);

  15.    free(str);

  16.    return(0);
  17. }


 楼主| antusheng 发表于 2022-6-11 20:09 | 显示全部楼层
 楼主| antusheng 发表于 2022-6-11 20:10 | 显示全部楼层
你试试你的电脑上,地址是不是跟我的不一样
asmine 发表于 2022-6-11 20:45 | 显示全部楼层
这是纯c么
mutable 发表于 2022-6-12 13:48 | 显示全部楼层
地址有问题?
jiekou001 发表于 2022-6-12 19:06 | 显示全部楼层
局部变量不需要使用这个吧,会自动清理吧
您需要登录后才可以回帖 登录 | 注册

本版积分规则

86

主题

1521

帖子

5

粉丝
快速回复 在线客服 返回列表 返回顶部