0

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?

JohnH
  • 2,713
  • 12
  • 21
  • 3
    Don't double tag questions as C and C++ *unless* it is specifically about those two languages (either trying to call one from the other or the differences in behavior) – UnholySheep Mar 14 '18 at 16:49
  • 1
    This isn't c++; C and C++ are not the same language. – UKMonkey Mar 14 '18 at 16:50
  • 2
    note that [`atoi` shouldn't be used](https://stackoverflow.com/q/17710018/995714) – phuclv Mar 14 '18 at 16:56
  • Change `while( count != position ){` to `while(*string && count != position ){` to check that you do not go off the end of the string – Ed Heal Mar 14 '18 at 16:57
  • You could also pack this whole function `chatAt()` into a single line: `char charAt(char *string, int position) { return string[position]; }` – ulmer-a Mar 14 '18 at 19:09
  • @LưuVĩnhPhúc Disagree... It's fine to use `atoi`, `gets` and not check `argc` *for quick prototype programs* where you can clearly see what's going on and where nobody else is going to run your program. – user253751 Mar 14 '18 at 23:22

1 Answers1

13

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.

tadman
  • 208,517
  • 23
  • 234
  • 262