I was trying to solve a question on HackerRank forum,but always i am getting the memory allocation error. Tried to fix the issue but lastly after lots of headbang,failed :( Please help me what's wrong here.(Thanks in advance) Question link : Hackerrank
int main(){
int testcases;
long  N,*segment,*range,max,*temp,*ptr,k,y1,y2,count;
scanf("%d",&testcases);
for(int t=1;t<=testcases;t++){
    max=0;
    scanf("%ld",&N);
    segment=malloc(sizeof(long)*N*2);
    temp=segment;
    for(long i=0;i<N*2;i++){
        scanf("%ld",(temp+i));
        if(*(temp+i)>max)
            max=*(temp+i);
    }
    range=malloc(sizeof(long));
    memset(range,0,sizeof(long)*max);
    ptr=range;
    k=0;
   while(k<(N*2-1)) {
    for(long a=*(temp+k);a<=*(temp+k+1);a++){
        ptr[a]=ptr[a]+1;
    }
       k=k+2;
   }
     y1=0,y2=0;  
    ptr=range;
     for(long i=0;i<max;i++){
        if(ptr[i]>y2){
            y2=y1;
            y1=ptr[i];
        }
     }
    count=0;
    temp=segment;
    for(long i=0;i<(N*2-1);i+=2 ){
        if((y1>=(*(temp+i))&&y1<=(*(temp+i+1))) || y2>=(*(temp+i))&&y2>=(*(temp+i+1)))
            count=count+1;
    }
    printf("Case %d:%ld\n",t,count);
    free(segment);
    free(range);
         }
return 0;}
Error:
solution: malloc.c:2372: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed.
 
    