I already know that there is no way to know if a pointer target still a valid allocation of it's already freed, so I'm trying to use pointer to pointer to solve this but it didn't work.
My objective is simply making print_block()
detect if block
pointer is Null or not.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void free_block(u_int8_t **_block) {
// Dereference
u_int8_t *block = *_block;
// Info
printf("free_block()\t-> %p Point To %p \n", &block, block);
// Free Block
free(block);
block = NULL;
}
void print_block(u_int8_t **_block) {
// Dereference
u_int8_t *block = *_block;
// Detectc if this block is freed
// This is the objective of this code
if(block == NULL) {
printf("print_block()\t-> %p Is Null.\n", block);
return;
}
// Info
printf("print_block()\t-> %p Point To %p -> ", &block, block);
// Print byte by byte
u_int8_t *p = block;
for(int i = 0; i < 3; i++) {
printf("0x%02X ", *(u_int8_t *)p);
p++;
}
printf("\n");
}
int main(void) {
// Allocat a block in the memory
u_int8_t *block = malloc(3 * sizeof(u_int8_t));
// Set all to zeros
memset(block, 0x00, 3);
// Info
printf("Main()\t\t\t-> %p Point To %p \n", &block, block);
// Print the block content
print_block(&block);
// Free the block
free_block(&block);
// Print the block content gain
// This shold print Null because
// we freed the block.
print_block(&block);
return 0;
}
Result
Main() -> 0x7fffd549cc58 Point To 0xfa42a0
print_block() -> 0x7fffd549cc28 Point To 0xfa42a0 -> 0x00 0x00 0x00
free_block() -> 0x7fffd549cc60 Point To 0xfa42a0
print_block() -> 0x7fffd549cc28 Point To 0xfa42a0 -> 0xA4 0x0F 0x00