why it is causing a stack fault..??

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kapadiamohit
    New Member
    • Mar 2013
    • 1

    why it is causing a stack fault..??

    Code:
    #include<stdio.h>
    	  #include<conio.h>
    
    	  void mergesort(int [],int,int);
    	  void merge(int [],int,int,int);
    
    	  void main()
    	  {
    		 int data[50],i,no_elements;
    		 printf("\n enter no. of elements :");
    		 scanf("%d",&no_elements);
    	
    		 printf("\n enter elements:");
    
    		 for(i=0;i<no_elements;i++)
    		 {
    			scanf("%d",&data[i]);
    		 }
    		
                     printf("\n entered array:");
    		 for(i=0;i<no_elements;i++)
    		 {
    			printf("%d",data[i]);
    		 }
    
    
    		 mergesort(data,0,no_elements-1);
    		 printf("\n sorted list:");
    
    		 /*for(i;i<no_elements;i++)
    		 {
    		  printf("%d",*(data+i));
    		 } */
    
    	  }
    
    	  void  mergesort(int a[],int i,int j)
    	  {
    		 int mid;
    		 if(i>=j)
    		 return ;
    		 else
    		 {
    		  mid=i+j/2;
    
    		  mergesort(a,i,mid);
    		  mergesort(a,mid+1,j);
    		  merge(a,i,j,mid);
    		 }
    	  }
    
    	  void merge(int a[],int i,int j,int mid)
    	  {
    		  int arbitary[100],start1,start2,k,last;
    		  start1=i;
    		  start2=mid+1;
    		  last=j;
    		  k=i;
    		while(start1<=mid && start2<=last)
    	        {
    		  if(a[start1]<=a[start2])
    		  {
    			arbitary[k]=a[start1];		              
    		k++;
    	        start1++;
    	}
    	else
            {
            arbitary[k]=a[start2];
    	k++;
    	start2++;
    	}
         }
    		  if(start1>mid)
    		  {
    			 while(start2<=last)
    			 arbitary[k++]=a[start2++];
    		  }
    		  else if(start2>j)
    		  {
    			 while(start1<=mid)
    			 arbitary[k++]=a[start1++];
    		  }
    	  }
    above program is for merge sort..

    why it is causing a stack fault..??
    Last edited by acoder; Mar 18 '13, 06:20 PM. Reason: Added text from post + title
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Start using your debugger. Set some breakpoints in each of your functions to see how the program is executing.

    Your merge function is part of a recursion and it creates an array on he stack. Do enough recursing and you could use up your allotted stack memory.

    If that's the case, start using malloc() to shift memory management to the heap.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      When you say "stack fault", what was the precise error message?

      Following line 11 you should verify that 0 < no_elements <= 50. Undefined behavior will occur if no_elements is outside this range.

      Comment

      Working...