I saw a video today on validating memory pointers and thought it was interesting enough to post about it...
The basic idea was that fopen checked that its passed filename was valid addressable memory(returned EFAULT if the address was invalid) and we could use that feature to validate memory addresses.
Note: The video producer did say that this wasn't a recommended practice. He stated that its better to write correct code that doesn't rely on this feature.
Code:
#include <asm-generic/errno-base.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int check_valid_address(void * ptr) {
FILE * temp = fopen((char*)ptr, "r");
if (temp) {
fclose(temp);
}else {
if (errno == EFAULT) {
return 1;
}
}
return 0;
}
int main(int argc, char ** argv) {
char * filename = NULL;
int x = 4143;
int * i_ptr = &x;
void * f_ptr = check_valid_address;
//Yeah! I know! Taking the address of a function and storing in a object pointer... Bad G4143
check_valid_address(filename)
? fprintf(stdout, "Invalid address: %p\n", filename)
: fprintf(stdout, "Valid address: %p\n", filename);
check_valid_address(i_ptr)
? fprintf(stdout, "Invalid address: %p\n", (void*)i_ptr)
: fprintf(stdout, "Valid address: %p\n", (void*)i_ptr);
check_valid_address(f_ptr)
? fprintf(stdout, "Invalid address: %p\n", (void*)f_ptr)
: fprintf(stdout, "Valid address: %p\n", (void*)f_ptr);
return EXIT_SUCCESS;
}
Invalid address: (nil)
Valid address: 0x7ffebd1c298c
Valid address: 0x55bd8e0d71c9
I always wondered why C never offered this feature in their standard library,