C: Progam not working

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • anvienhponline
    New Member
    • Aug 2014
    • 1

    C: Progam not working

    My C program isn't reaching the "return 0;" statement:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
     
    char *invertString( const char *const str );
     
    int main( void )
    {
        char string[ 25 ];
        char *ptr;
     
        printf( "Enter a string without whitespace: " );
        scanf( "%25s", string );
     
        ptr = invertString( string );
     
        if ( ptr != NULL )
        {
            printf( "The inverted string is %s.\n", ptr );
        }
        else
        {
            printf( "A memory error occurred.\n" );
        }
     
        printf( "LINE %d.\n", __LINE__ );
     
        return 0;
    }
     
    char *invertString( const char *const str )
    {
        unsigned int i;
        unsigned int j;
        unsigned int lengthOfStr = strlen( str );
        char *newStr = ( char * )malloc( ( lengthOfStr + 1 ) * sizeof( char ) );
     
        if ( newStr == NULL )
        {
            printf( "ERROR!" );
            return newStr;
        }
     
        for ( i = lengthOfStr - 1, j = 0 ; i >= 0 ; --i, ++j )
        {
            *( newStr + j ) = *( str + i );
        }
     
        *( newStr + j ) = '\0';
     
        return newStr;
    }
    The program is supposed to invert a string by creating a new string and there putting the contents of the original string in reverse order. The problem is, it isn't reaching the "return 0;" statement. I even added the statement

    Code:
    printf( "ERROR!" );
    inside the invertString function to check whether a memory error is occurring, but it isn't executing. What is possibly going on? Thanks in advance.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    This code from invertString:
    Code:
    char *newStr = ( char * )malloc( ( lengthOfStr + 1 ) * sizeof( char ) );
     
        if ( newStr == NULL )
        {
            printf( "ERROR!" );
            return newStr;
        }
    will only print ERRROR! if malloc() returns a null pointer. This will only happen if your program runs out of heap memory. Since this is highly unlikely, you never see this ERROR!

    Then there is this code in invertString:
    Code:
    for ( i = lengthOfStr - 1, j = 0 ; i >= 0 ; --i, ++j )
         {
            *( newStr + j ) = *( str + i );
         }
    Assume, for the moment, your string is "A". lengthOfStr is 1. Now 1 is subtracted starting i at 0. The loop continues if i >=0. The A is inverted. Now comes --i for the second cycle. i is now -1 When you hit str+i you crash trying to access memory that's not part of your program.
    Last edited by weaknessforcats; Aug 12 '14, 02:12 AM.

    Comment

    Working...