Contents
Dangling Pointers?
The most common error with pointers and memory management is dangling/crazy pointers. Sometimes programmers fail to initialize a pointer with a valid address, so this type of initialization is called dangling pointer in C.
A dangling pointer occurs when objects are removed from memory without updating the value of the pointer, or when objects are destroyed when removed from memory. In this case, the pointer points to the allocated memory. Dangling pointers can point to code or memory containing code. If we give this parameter a value, it will overwrite the value of the program code or operating system instructions; In this case, the program will display unwanted results and may even crash. If the memory is allocated to another process, dereferencing the dangling pointer will cause a segmentation fault.
Example Using free() function to de-allocate the memory.
#include <stdio.h>
#include <stdlib.h> // Include the stdlib.h header for the free() function
int main() {
// Dynamically allocate memory for an integer array
int *arr = (int *)malloc(5 * sizeof(int));
if (arr == NULL) {
printf(“Memory allocation failed.\n”);
return 1;
}
// Use the dynamically allocated memory as needed
for (int i = 0; i < 5; i++) {
arr[i] = i * 10;
}
// Deallocate the dynamically allocated memory using free()
free(arr);
// After calling free(), the memory should not be accessed anymore
// Accessing the memory after deallocation can lead to undefined behavior
return 0;
}
Output
Memory allocated successfully.
Memory deallocated successfully.
In the above code, we have created two variables, i.e., *ptr and a where ‘ptr’ is a pointer and ‘a’ is a integer variable. The *ptr is a pointer variable which is created with the help of malloc() function. As we know that malloc() function returns void, so we use int * to convert void pointer into int pointer.
Variable goes out of the scope
If the switch is extinguished, it means that the life cycle has ended and it cannot be activated anymore. This usually occurs when the block post is abnormally out. In C, variables declared inside a block (within curly braces {}) contain the block, which means they can only be accessed from within that block.
Example
#include <stdio.h>
int main() {
// Variable ‘x’ declared within the main function block
int x = 10;
// Print the value of ‘x’
printf(“Value of x inside main: %d\n”, x);
// Start a new block
{
// Variable ‘y’ declared within the inner block
int y = 20;
// Print the value of ‘y’ inside the inner block
printf(“Value of y inside inner block: %d\n”, y);
}
// ‘y’ goes out of scope here and is no longer accessible
// Attempting to access ‘y’ here would result in a compilation error
return 0;
}
Output
Value of x inside main: 10
Value of y inside inner block: 20