-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrealloc.cpp
More file actions
29 lines (23 loc) · 739 Bytes
/
Copy pathrealloc.cpp
File metadata and controls
29 lines (23 loc) · 739 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *i = (int *)malloc(sizeof(int));
i[0] = 12;
printf("%p %d", i, i[0]);
// reserve memory for two integers
int *p = (int *)malloc(2 * sizeof(int));
p[0] = 1;
p[1] = 2;
// resize memory to hold four integers
p = (int *)realloc(p, 4 * sizeof(int));
p[2] = 3;
p[3] = 4;
// resize memory again to hold two integers
p = (int *)realloc(p, 2 * sizeof(int));
printf("address=%p, value=%d\n", p + 0, *(p + 0)); // valid
printf("address=%p, value=%d\n", p + 1, *(p + 1)); // valid
printf("address=%p, value=%d\n", p + 2, *(p + 2)); // INVALID
printf("address=%p, value=%d\n", p + 3, *(p + 3)); // INVALID
return 0;
}