SIGSEGV error

error
runtime
runtime-error
sigsegv

#1

Problem: Grab a ladder.
http://www.codechef.com/ICD2015/problems/ICD02

#include <stdio.h>
#include <stdlib.h>
int *c1;
int main()
{
int i=0,j=0,cases=0,n=0,ladder=0,h=0;
FILE *fp;
FILE *fp1;

fp=fopen("test.txt", "r");
fp1=fopen("out.txt", "w");
fscanf(fp,"%d",&cases);
for(i=0; i<cases; i++)
{
    ladder=0;
    fscanf(fp,"%d",&n);
    c1 =malloc(n*sizeof(int));
    for(j=0;j<n;j++)
    {
        fscanf(fp,"%d",&c1[j]);
    }
    h=c1[0];
    for(j=0;j<n-1;j++)
    {
        if(c1[j]<c1[j+1])
        {
            if(c1[j+1]>h)
            {
                h=c1[j+1];
                ladder++;
            }
        }
    }
    fprintf(fp1,"%d ",ladder);
}
fclose(fp);
free(c1);
return 0;

}


#2

From the CodeChef wiki:

“A SIGSEGV is an error(signal) caused by an invalid memory reference or a segmentation fault. You are probably trying to access an array element out of bounds or trying to use too much memory. Some of the other causes of a segmentation fault are : Using uninitialized pointers, dereference of NULL pointers, accessing memory that the program doesn’t own.”

I’m not really a C programmer, but as far as I can see, you really don’t need the two files, test.txt and out.txt (memory that the program doesn’t own). CodeChef problems require you to simply read and write from the console.

Further if you’re using C++, may I suggest using std::vector instead of malloc.


#3

The error is because you are not type casting the allocated memory. By default malloc allocates char.

So just replace this statement c1 =malloc(n*sizeof(int)); by c1 = (int *) malloc ( n * sizeof( int ) );

Hope it works!

Also, unlike many other sites(like code jam) you have to take your input in standard input and give output to standard output, not to any file.