-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathmemory_leak3.c
More file actions
34 lines (28 loc) · 756 Bytes
/
Copy pathmemory_leak3.c
File metadata and controls
34 lines (28 loc) · 756 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
30
31
32
33
34
/*
This program leaks memory but only in one of the if branch.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
// Allocate memory
char *buffer = (char*)malloc(sizeof(char));
if (buffer == NULL) {
return 2; // Return 2 in case memory allocation fails
}
// Open a common file
FILE *file = fopen("/etc/passwd", "r");
if (file == NULL) {
return -1; // Return -1 and leak memory if file opening fails
}
// Read the first character
char firstChar = fgetc(file);
if (firstChar != EOF) {
*buffer = firstChar;
printf("First character in file: %c\n", *buffer);
}
// Close file and free memory
fclose(file);
free(buffer);
return 0;
}