Reputation: 139
I write such code to help me understand the usage of realloc()
function. Maybe there are some problems in the follow code.
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 }
To my surprise,the running result of program are different!
Under mac os x 10.9.2, the result is:
------------dynamic_memory_management_func------------
str1 value: 0x7ff7f1c03940 [0123456789AB]
str2 value: 0x7ff7f1c03940 [0123456789AB]
str3 value: 0x7ff7f1c03940 [0123456789AB]
str4 value: 0x7ff7f1c03950 [0123456789ABCDEFGHIJKLMN]
Under ubuntu 12.04 LTS, the result is:
------------dynamic_memory_management_func------------
str1 value: 0xf6e010 [0123456789AB]
str2 value: 0xf6e010 [0123456789AB]
str3 value: 0xf6e010 [0123456789ABCDEFGHIGKLMN]
str4 value: 0xf6e010 [0123456789ABCDEFGHIGKLMN]
As you've seen, The addresses of pointer of str4 are different. What make it happened?
Upvotes: 1
Views: 67
Reputation: 108988
It's an expected result.
The memory malloc()
chooses each time it is called depends on many many things. It probably chooses different memory on the same computer at different times! Let alone on different computers.
The important thing is the contents of the memory. And they're (about) the same, as expected, on your test.
However you have a few errors:
line 15: str1
is invalid. It has been made invalid be the previous call to realloc()
.
line 16: the contents of str2
are not a "string". it does not have a proper terminator. It is invalid to print it with printf()
line 27: str3
is invalid. It has been made invalid be the previous call to realloc()
.
Upvotes: 7