-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy path04.c
46 lines (35 loc) · 1.17 KB
/
04.c
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
// Purpose: Demonstrate NULL pointer initialization and safe usage.
// Key points:
// 1. Initialize pointers to NULL when they don't yet point to valid data.
// 2. Check pointers for NULL before using to avoid crashes.
// 3. NULL checks allow graceful handling of uninitialized or failed allocations.
#include <stdio.h>
#include <stdlib.h>
int main() {
// Initialize pointer to NULL
int* ptr = NULL;
printf("1. Initial ptr value: %p\n", (void*)ptr);
// Check for NULL before using
if (ptr == NULL) {
printf("2. ptr is NULL, cannot dereference\n");
}
// Allocate memory
ptr = malloc(sizeof(int));
if (ptr == NULL) {
printf("3. Memory allocation failed\n");
return 1;
}
printf("4. After allocation, ptr value: %p\n", (void*)ptr);
// Safe to use ptr after NULL check
*ptr = 42;
printf("5. Value at ptr: %d\n", *ptr);
// Clean up
free(ptr);
ptr = NULL; // Set to NULL after freeing
printf("6. After free, ptr value: %p\n", (void*)ptr);
// Demonstrate safety of NULL check after free
if (ptr == NULL) {
printf("7. ptr is NULL, safely avoided use after free\n");
}
return 0;
}