Thread: Run-Time Check Failure #2

  1. #1
    Registered User
    Join Date
    Aug 2011
    Posts
    385

    Run-Time Check Failure #2

    The following code runs fine with Pelles C but terminates on MSVC 2010 with an error message
    "Run-Time Check Failure #2 - Stack around the variable 'c' was corrupted."

    Code:
    #include<stdio.h>
    #include<string.h>
    #include<ctype.h>
    
    int main()
    {
    	char s[20][20],*c[20];
    	FILE *fp;
    	int i,j,words;
    
    	fp=fopen("acc.txt","r");
    
    	words=i=0;
    	while(fscanf(fp,"%s",s[i])!=EOF)
    	{	words++; i++;	}
    
    	for(i=0;i<words;i++)
    		c[i]=s[i];
    
    	for(i=1;i<words;i++)
    	{
    		for(j=1;j<=words-i;j++)
    		{
    			if(strcmp(c[j-1],c[j])>0)
    			{
    				c[20]=c[j-1];
    				c[j-1]=c[j];
    				c[j]=c[20];
    			}
    		}
    	}
    
    	fclose(fp);
    	fp=fopen("acc.txt","w");
    	for(i=0;i<words;i++)
    		fprintf(fp,"%s ",c[i]);
    }
    Can someone tell me whats wrong??

  2. #2
    Registered User
    Join Date
    Aug 2011
    Posts
    385
    The program is a sorting program which reads words from a file and arranges them in alphabetical order..

  3. #3
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    You never check fp to make sure it opened correctly, so calling fscanf on it if it failed could crash your program. You need to actually return a value from main, usually 0 for success. You have no bounds checking on the data you read in from your file. If you have a word that is over 20 chars, it will overflow s[i]. If you have more than 20 words, you will overflow s in your read loop. Again, when you copy from s[i] to c[i], you don't ensure words < 20. On line 20, you do j <= words, but if words is 20 or more, that's an overflow when you access c[j]. Also, on lines 26 and 28, you use c[20], which is out of bounds. In C, arrays start at 0 and go to size-1, so you only have c[0]...c[19].

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Stange that after 270 posts someone could be not aware that arrays go from 0 to n-1?
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 11-10-2011, 06:00 PM
  2. Run-Time Check Failure #2
    By mjskolly in forum C Programming
    Replies: 6
    Last Post: 08-23-2011, 07:58 AM
  3. Run-Time Check Failure #2 help
    By lazysam in forum C Programming
    Replies: 2
    Last Post: 04-29-2009, 09:14 AM
  4. Replies: 14
    Last Post: 11-17-2008, 12:31 PM
  5. Replies: 3
    Last Post: 05-22-2007, 11:42 PM