Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   UNKNOWN! runtime error (http://www.go4expert.com/forums/unknown-runtime-error-t21475/)

lionaneesh 24Mar2010 00:55

UNKNOWN! runtime error
 
Code:

#include<stdio.h>

void reverse(char str[]);

int main()
{
    char str[100];
    int i;

    printf("Enter to reverse : ");
    scanf("%s",str);
    reverse(str);
    return(0);
}
/* Function */

void reverse(char str[])
{

    int i;
    for(i=99;i>=0;i--)
    {
        printf("%c",str[i]);
    }
    putchar('\n');
}

:embarasse:embarasse:embarasse:embarasse:embarasse :embarasse:embarasse:embarasse:embarasse:embarasse :embarasse:embarasse\


Why there is a runtime error in the above programme..........

help!!!!!!
URJENT!!!!!!!!

virxen 24Mar2010 04:11

Re: UNKNOWN! runtime error
 
Code:

#include<stdio.h>
#include <string.h>

void reverse(char str[]);

int main()
{
    char str[100];
    int i;

    printf("Enter to reverse : ");
    scanf("%s",str);
    reverse(str);
    return(0);
}
/* Function */

void reverse(char str[])
{

    int i;
    int z=strlen(str);
    for(i=z-1;i>=0;i--)
    {
        printf("%c",str[i]);
    }
    putchar('\n');
}

the error is that you reserve 100 positions in memory for the string entered
but it uses actually only those the user enter.

so if i enter the word car-->'c' 'a' 'r' '\0' so it uses 4 positions instead of 100
so instead of starting from the end of 100positions you must start from the end of 4positions down to 0

xpi0t0s 24Mar2010 14:41

Re: UNKNOWN! runtime error
 
That doesn't explain why there would be a runtime error. It would explain why garbage is displayed and if I modify the program to add
Code:

        for (i=0; i<100; i++)
                str[i]='~';

to main just after the int i declaration, the output is:
Enter to reverse : hello
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ olleh

but even without this modification I don't get a runtime error (in Visual Studio 2008 building the program in Debug mode).

When it prompted you to enter a string, did you enter more than 100 characters? That might cause a runtime error - this is the infamous "buffer overflow" bug.

If not then I can only suggest this is a compiler bug. Maybe the RTL has a problem with %c for non-printable characters. You can test this hypothesis with a simple program:
Code:

printf("Starting test\n");
fflush(stdout);
for (i=0; i<256; i++)
{
  printf("%d %c ",i,i);
  fflush(stdout);
}

The fflush ensures that the last character before the runtime error is displayed; normally output is buffered which can cause confusion when a program crashes - it looks like it crashed before it actually went tits up.


All times are GMT +5.5. The time now is 10:46.