I don't know why this program crashs when the alarm handler finishs its work, due to malloc statement (LINE1) although it is never been called
When I comment LINE1 OR LINE2 the code continues without any problems, but when commenting LINE3 the program still crashs
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void handler (int sig) {
printf ("Hi I'm at handler\n");
}
int main() {
int *pm, f = 0;
struct sigaction sa;
sa.sa_handler = &handler;
sigaction (SIGALRM, &sa, NULL);
alarm (2); // LINE1
while (1) {
if (f == 1) {
pm = (int *) malloc (sizeof (int)); // LINE2
if (pm)
printf ("memory allocated at loop\n");
}
else {
printf ("Wait\n");
usleep (200000); // LINE3
}
}
return 0;
}
Result:
Wait
Wait
Wait
Wait
Wait
Wait
Wait
Wait
Wait
Wait
Hi I'm at handler
Segmentation fault (core dumped)
Notes:
This problem faces me in a larger application that can't be posted here so I wrote this program to show it I'm working under Ubuntu and compiling with gcc