What is the correct way to clear with free()dynamically allocated data in C when using a signal?
There is an example with shared memory, and the solution used is to declare a global variable, but it seems not very clean and safe.
This is sample code with an array of dynamically distributed structure that is not properly cleaned.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
typedef struct {
int val;
} mystruct_t;
void sigquit(int sig) {
signal(sig, SIG_IGN);
printf("Child killed\n");
exit(0);
}
int
main()
{
int n = 10;
mystruct_t **struct_a = generatearray(n);
pid_t pid = fork();
if (pid == 0) {
printf("Child process. My pid is %d and my parent id is %d.\n",
getpid(), getppid());
if (signal(SIGQUIT, sigquit) == SIG_ERR) {
printf("SIGINT install error\n");
exit(1);
}
while(1);
}
else {
printf("Parent process. My pid is %d and my parent id is %d.\n",
getpid(), pid);
sleep(1);
kill(pid, SIGQUIT);
sleep(5);
}
return 0;
}
What method would you use to solve this problem?
source
share