John Scott
John Scott

Reputation: 1

Why is my program crashing when I try to print a char pointer

So i have this program for my C class its to make a function that will tell you the character at a certain number position in the string.

char charAt( char * string, int position );

int main( int argc, char * argv[ ] ) {

    int pos = atoi( argv[3] );

    if( strcmp( argv[1], "charAt" ) == 0 )
    {
        printf( "%s", charAt( argv[2], pos ) );
    }    
}



char charAt( char *string, int position ){
    int count = 0;
    while( count != position ){
        string++;
        count++;
    }

    return *string;
}

When i compile it shows no errors when i run it in the command line using

name charAt string 3

It crashes at

printf( "%s", charAt( argv[2], pos) );

that line Why when i pass the char pointer to the printf function does it crash?

Upvotes: 0

Views: 395

Answers (1)

tadman
tadman

Reputation: 211740

You're referencing argv without checking that argc is high enough to permit those references. What if argc is only 1?

The real problem is using %s to display a single character. That needs to be %c. Using %s is going to treat that as a character pointer, which it isn't, and then your program is deep into undefined behaviour.

Upvotes: 13

Related Questions