dimanche 28 juin 2015

"Adress out of bound" when accessing second element of a pointer passed to a function

I have this function:

int scan_arguments(int *words_count, char ***words, char **file)
{
    /* If the first argument is equal to "/f" copy the second argument in the file variable */
    if (*words_count > 2 && !strncmp(*words[0], "/f", 2)) {
        if(!(file = malloc(strlen(*words[1]) + 1))) {
            printf("Allocation error");
            return 1;
        }
        strcpy(*file, *words[1]);
        words += 2;
        words_count -= 2;
}

And I call it this way from my main function:

int main(int argc, char **argc)
{
    char *file = "", **words;
    int words_count;

    /* Copy the arguments and discard the program name */
    words = argv + 1; 
    words_count = argc - 1;

    scan_arguments(&words_count, &words, &file);
}

The purpose of my function is to check if the first argument is "/f" and, if it is, store the second argument in the file string.

The problem is that when execution reaches the strlen(*words[1]) part, the program stops working and from the debugger I get "Adress out of bound". I can't understand what's the problem, because *words[0] gets evalueted correctly.

Sorry if it is maybe a simple question but it's my first serious program with pointers and I still have some difficulties.

Thanks for your help!

Aucun commentaire:

Enregistrer un commentaire