-2

I am writing a function to dynamically allocate a string array from my dictionary file that will be accessed through command line arguments. I keep getting segmentation fault 11 and cannot figure out why

int
allocateArray(int count)
    {
    int i;
    char **array;
    char **argv;
    char *fileName = argv[1];
    FILE *fp = fopen(fileName, "r");
    count = countTokens(argv);
    array = malloc(sizeof(char *) * count);
    if (array == 0)
        {
        fprintf(stderr, "memory allocation failed\n");
        exit(1);
        }
    for(i = 0; i < count; i++)
        {
        array[i] = malloc(count);
        }
    for (i = 0; i < count; i ++)
        {
        fscanf (fp,"%s", array[i]);
        }
    free(array);
    fclose(fp);
    return **array;
    }
Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85

1 Answers1

1

In char *fileName = argv[1];, you dereference argv[1]. However, it isn't pointing to a memory location you own because you haven't allocated any memory to it on the previous line char **argv;.

You seem to be having some misunderstanding as to the command line arguments (CLA). In int main(int argc, char **argv), argv is a CLA (as you seem to be already aware of). However, when main() calls another function, the CLA doesn't automatically get passed to it.

As a result, in your int allocateArray(int count) function, the argv that you declared is just another local variable. You would need to explicitly pass the argv from main() to allocateArray().

The same goes for the other pointer variables in your code. I would recommend that you read up on "Scope and Lifetime of Variables" from a standard book. (I don't mean this in a condescending way.)

Masked Man
  • 1
  • 7
  • 40
  • 80