Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riking/345a4d1b3bd0a984a779eced2c05c394 to your computer and use it in GitHub Desktop.
Save riking/345a4d1b3bd0a984a779eced2c05c394 to your computer and use it in GitHub Desktop.
#include <signal.h>
#include <stdio.h>
#include <malloc.h>
#include <setjmp.h>
#include <stdbool.h>
static jmp_buf omg;
struct list {
char dummy[16384];
struct list *next;
};
static void handler(int sig, siginfo_t *si, void *unused)
{
longjmp(omg, 1);
}
bool list_cycle(struct list *list)
{
struct sigaction sa;
struct sigaction old;
struct list *prev;
sa.sa_flags = SA_SIGINFO;
sigemptyset(&sa.sa_mask);
sa.sa_sigaction = handler;
if (sigaction(SIGABRT, &sa, &old) == -1) {
perror("sigaction");
return -1;
}
if (setjmp(omg)) {
if (sigaction(SIGABRT, &old, NULL) == -1) {
// perror("sigaction"); // ignore
}
return true;
}
while (list->next) {
prev = list;
list = list->next;
free(prev);
}
free(list);
if (sigaction(SIGABRT, &old, NULL) == -1) {
perror("sigaction");
return -1;
}
return false;
}
int main (int argc, char **argv) {
struct list *test, *test2;
test = malloc(sizeof(struct list));
test2 = malloc(sizeof(struct list));
test->next = test2;
test2->next = test;
if (list_cycle(test) == true) {
printf("loop\n");
} else {
printf("no loop\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment