problem with strcat() and argv[]

Hello,

i have the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <string.h>
#include <iostream.h>

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

    if (argc < 2){
         cout << "\a";
         return -1;
    }

    char file[50];
    
    strcat(file, "CWE");
    strcat(file, argv[1]);
    strcat(file, ".txt");
    
    cout << file << "\n\n";
    cout << "\n";
    //system("PAUSE");
    return 0;
}


i receive segmentation fault. The problem must be in line 9. Overflow error probably. Any idea?

(We assume that the user will type an argv[1] argument with maximum 5 characters.)
http://www.cplusplus.com/reference/clibrary/cstring/strcat/

strcat expects file to be a null-terminated string. This means it is an array of char with a zero value on the end. You have made an array of char, named file, with random values in it. Set the first char to zero to mark the end of the c-style string (i.e. to mark it as an empty c-style string).

As an aside, if you're going to code in C++, use std::string instead of an array of char. It's so much safer and easier.
Last edited on
Topic archived. No new replies allowed.