Search code examples
crecursioninfinite-loop

SIGXCPU error in C program


The following program is not producing output. It enters the for loop and takes one value (via scanf) but after that the code block stops execution. Ideone (an online compiler and debugging tool) says that SIGXCPU signal is generated.

#include <stdio.h>
#include <stdlib.h>

long fact(int);
int z(int);

int main()
{
    int i, n; 
    scanf("%d",&n); 
    int a[10];long b[10];
    int c[10];
    for(i=0;i<n;i++)
    {
        scanf("%d", &a[i]);
        b[i]=fact(a[i]);
        c[i]=z(b[i]);
    }
    printf("\n");
    for(i=0; i<n; i++)
    {
        printf("%d", c[i]);
    }
    return 0;
}

long fact(int m)
{
    if (m==1) return 1;
    else return (m*fact(m-1));
}

int z (int s)
{
    int c=0, temp;
    temp=s%10;
    if(temp!=0) return c;
    else
    {
        c++; z(temp);
    }
}

What does the SIGXCPU signal mean?


Solution

  • The SIGXCPU signal is sent each second to a process after it exceeds its limit on consumed processor time (RLIMIT_CPU), or, for realtime processes, its limit on running without sleeping. The problem here is with your recursive z function that does not stop and calls itself again and again (and causes a stack overflow). Fix its stop condition.

    From the signal man page:

    Signal | Default Action | Description
    -------+----------------+-------------------------
    SIGXCPU| A              | CPU time limit exceeded.
    

    The default actions are as follows:

    A - Abnormal termination of the process. Additionally, implementation-defined abnormal termination actions, such as creation of a core file, may occur.