Search code examples
cmultidimensional-arrayundefined-behaviorc-stringsstrcpy

strcpy segfault copying file content to array


This is my code

char url[MAX_WORD + 1];
char *urls[MAX_WORD + 1];
//char word[MAX_WORD + 1];

while(fscanf(fp, "%100s", url) == 1) {
    strcpy(urls[index], url);
    index++;
}

This is the error I'm getting on valgrind:

==43177== Process terminating with default action of signal 11 (SIGSEGV)
==43177==  Access not within mapped region at address 0x4844000
==43177==    at 0x4838DC8: strcpy (vg_replace_strmem.c:512)
==43177==    by 0x109898: generateInvertedIndex (invertedIndex.c:102)
==43177==    by 0x1092B4: test1 (testInvertedIndex.c:36)
==43177==    by 0x109244: main (testInvertedIndex.c:23)

This is the content of the file it is copying from

nasa.txt
news1.txt
file11.txt
mixed.txt
planets.txt
file21.txt
info31.txt

I don't know how I am getting this error. I just want to copy the content of the file to an array of Urls. But it doesn't work.


Solution

  • You have an array of uninitialized pointers or null pointers if the array is declared in the file scope

    char *urls[MAX_WORD + 1];
    

    So this call

    strcpy(urls[index], url);
    

    invokes undefined behavior.

    It seems what you need is to declare a two-dimensional array like for example

    char urls[MAX_WORD + 1][MAX_WORD + 1];
    

    Or in the original array allocate dynamically memory for the stored string. Something like

    urls[index] = malloc( strlen( url ) + 1 );
    if ( urls[index] != NULL ) strcpy(urls[index], url);
    else /* some error processing */;