-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathmemory_leak2.c
More file actions
69 lines (59 loc) · 2.21 KB
/
Copy pathmemory_leak2.c
File metadata and controls
69 lines (59 loc) · 2.21 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
This program constructs a slightly more complicated memory leak scenario.
The program allocates memory for an array of structs, each of which contains
an inner array.
The program then initializes the inner arrays with values.
The program then forgets to free the inner arrays before freeing the outer
array, causing a memory leak.
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int* innerArray;
int size;
} MyStruct;
int main() {
int numStructs = 5; // Number of structs in the meta-array
MyStruct **outerArray = (MyStruct**)malloc(numStructs * sizeof(MyStruct*));
if (outerArray == NULL) {
perror("Failed to allocate memory for outerArray");
return 1;
}
// Allocate and initialize each struct and its inner array
for (int i = 0; i < numStructs; ++i) {
outerArray[i] = (MyStruct*)malloc(sizeof(MyStruct));
if (outerArray[i] == NULL) {
perror("Failed to allocate memory for outerArray element");
// Free already allocated memory before exiting
for (int j = 0; j < i; j++) {
free(outerArray[j]->innerArray);
free(outerArray[j]);
}
free(outerArray);
return 1;
}
outerArray[i]->size = 10; // Size of the inner array
outerArray[i]->innerArray = (int*)malloc(outerArray[i]->size * sizeof(int));
if (outerArray[i]->innerArray == NULL) {
perror("Failed to allocate memory for innerArray");
// Free already allocated memory before exiting
for (int j = 0; j <= i; j++) {
free(outerArray[j]);
}
free(outerArray);
return 1;
}
// Initialize the inner array with values
for (int j = 0; j < outerArray[i]->size; j++) {
outerArray[i]->innerArray[j] = j;
}
}
// ... Use outerArray and its inner arrays ...
// Free the meta-array but forget to free the inner arrays
for (int i = 0; i < numStructs; ++i) {
// Memory leak: innerArray not freed
free(outerArray[i]); // Only freeing the struct, not its innerArray
}
free(outerArray);
return 0;
}