Skip to content

Instantly share code, notes, and snippets.

@opsJson
Last active April 13, 2024 18:54
Show Gist options
  • Save opsJson/fee3ce14d66e4616e2d11c0f98c08a52 to your computer and use it in GitHub Desktop.
Save opsJson/fee3ce14d66e4616e2d11c0f98c08a52 to your computer and use it in GitHub Desktop.
SegFault check
#include <stdlib.h>
#include <stdio.h>
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
#include <fcntl.h>
#define PIPE(X) _pipe(X, 2, O_RAW)
#else
#include <unistd.h>
#define PIPE(X) pipe(X)
#endif
int p(void *ptr) {
int fd[2];
if (ptr == NULL) return 0;
if (PIPE(fd)) return 0;
if (write(fd[1], ptr, 1) == -1) return 0;
return 1;
}
#define free(ptr) {ptr = 0; free(ptr);}
int main() {
//uninitialized ptr returns 0
char *c;
printf("%i\n", p(c));
//NULL ptr returns 0
c = 0;
printf("%i\n", p(c));
//invalid ptr returns 0
c = (char*)0x234890a;
printf("%i\n", p(c));
//freed ptr returns 0
free(c);
printf("%i\n", p(c));
//allocated ptr returns 1
c = malloc(10);
printf("%i\n", p(c));
//valid ptr returns 1
char f = 'F';
c = &f;
printf("%i\n", p(c));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment