Question

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
}
Was it helpful?

Solution

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.

OTHER TIPS

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; 

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)

It should be

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

or better still

snprintf(filename, sizeof(filename), "%s", argv[1]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top