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

    // checked for right number of arguments

    // reading pack name
    char* filename[MAX_STR_LEN];
    strcpy(*filename, argv[1]);  // seg fault here
}
George Brighton
  • 5,131
  • 9
  • 27
  • 36

4 Answers4

2
char* filename[MAX_STR_LEN];

That declares an array of pointers, and doesn't initialise them to point to anything. Dereferencing them gives undefined behaviour; if you're lucky, a segmentation fault.

You probably meant to declare an array of characters to contain the string:

char filename[MAX_STR_LEN];
strcpy(filename, argv[1]);

Now you just need to make sure the array is large enough; or stop mucking around with low-level C artifacts and use std::string instead.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0
char filename[MAX_STR_LEN] // without the * 
strcpy(filename, argv[1]); // without the *

better (to avoid stackoverflow ! (lol) ):

strncpy( filename, argv[1], sizeof(filename)-1 );
filename[ sizeof(filename)-1 ] = 0; 
manuell
  • 7,528
  • 5
  • 31
  • 58
  • Preventing stack corruption is a worthy goal, but it doesn't pay to replace it with corrupted data. `strncpy` is hard to use right. Just use `strlen` and give an error message if the array is too small; if it's okay, `strcpy`. – Pete Becker Nov 06 '13 at 17:48
  • @PeteBecker I don't like corrupted data and would use strlen + error message if necessary. What may be the problem with my use of strncpy? – manuell Nov 06 '13 at 17:58
  • There's no direct way to check whether the copy got truncated, so you end up having to call `strlen` anyway. – Pete Becker Nov 06 '13 at 18:01
0

1) filename is an array of *char. I'm not sure that's what you want to be doing. You probably want to have

char filename[FOO];

2) strcpy expects a (char *, const char *), which you're passing it, but there's no allocated space here for you, see (1)

Dan L
  • 325
  • 1
  • 6
0

It should be

char filename[MAX_STR_LEN];
.
.
strcpy(filename, argv[1]);

or better still

snprintf(filename, sizeof(filename), "%s", argv[1]);
Arun Taylor
  • 1,574
  • 8
  • 5
  • @Pete Becker, yes - you are right. The filename needs to be declared as an array of char. – Arun Taylor Nov 06 '13 at 17:48
  • beware, snprintf may gives you a string WITHOUT the final 0. Use sizeof(filename)-1 – manuell Nov 06 '13 at 17:50
  • @manuell - `snprintf` copies up to `n-1` characters, so it's okay to give the exact size of the array. But it won't tell you that the file name got truncated, so it's not really very helpful. Just start with `strlen` to see whether the buffer is big enough. If it is, copy the characters. If it isn't, give an error message and don't copy. – Pete Becker Nov 06 '13 at 17:59
  • @manuell, the OpenBSD man page says it will write at most size-1 chars followed by null. – Arun Taylor Nov 06 '13 at 17:59
  • @ArunTaylor MY BAD! I was reading Microsoft documentation of _snprintf... ==>[] – manuell Nov 06 '13 at 18:04