我编写这样的代码来帮助我理解realloc()函数的用法.也许在以下代码中存在一些问题.
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5
6 void dynamic_memory_management_func()
7 {
8 printf("------------dynamic_memory_management_func------------\n");
9
10 char *str1 = (char *)malloc(16);
11 memset(str1, 0, 16);
12 strcpy(str1, "0123456789AB");
13 char *str2 = realloc(str1, 8);
14
15 printf("str1 value: %p [%s]\n", str1, str1);
16 printf("str2 value: %p [%s]\n", str2, str2);
17
18 free(str2);
19 str2 = NULL;
20
21 char *str3 = (char *)malloc(16);
22 memset(str3, 0, 16);
23 strcpy(str3, "0123456789AB");
24 char *str4 = realloc(str3, 64);
25 strcpy(str4 + 12, "CDEFGHIJKLMN");
26
27 printf("str3 value: %p [%s]\n", str3, str3);
28 printf("str4 value: %p [%s]\n", str4, str4);
29
30 free(str4);
31 str4 = NULL;
32
33 }
34
35 int main(int argc, char *argv[])
36 {
37 dynamic_memory_management_func();
38 return 0;
39 }
Run Code Online (Sandbox Code Playgroud)
令我惊讶的是,程序的运行结果是不同的!
在mac os x 10.9.2下,结果是:
------------dynamic_memory_management_func------------
str1 value: 0x7ff7f1c03940 [0123456789AB]
str2 value: 0x7ff7f1c03940 [0123456789AB]
str3 value: 0x7ff7f1c03940 [0123456789AB]
str4 value: 0x7ff7f1c03950 [0123456789ABCDEFGHIJKLMN]
Run Code Online (Sandbox Code Playgroud)
在ubuntu 12.04 LTS下,结果是:
------------dynamic_memory_management_func------------
str1 value: 0xf6e010 [0123456789AB]
str2 value: 0xf6e010 [0123456789AB]
str3 value: 0xf6e010 [0123456789ABCDEFGHIGKLMN]
str4 value: 0xf6e010 [0123456789ABCDEFGHIGKLMN]
Run Code Online (Sandbox Code Playgroud)
如您所见,str4指针的地址不同.是什么让它发生了?
这是预期的结果.
malloc()每次调用时选择的内存取决于很多东西.它可能在不同的时间在同一台计算机上选择不同的内存!更别说在不同的电脑上了.
重要的是内存的内容.在测试中,他们(大约)和预期一样.
但是你有一些错误:
第15行:str1无效.以前的调用已被视为无效realloc().
第16行:内容str2不是"字符串".它没有合适的终结器.打印它是无效的printf()
第27行:str3无效.以前的调用已被视为无效realloc().
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |