-1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Your `urls` pointers do not point anywhere. You didn't initialize them. – user17732522 Mar 03 '22 at 10:14
  • 1
    `char *urls[MAX_WORD + 1];` is an array of `MAX_WORD + 1` **pointers** ; nothing more. Until you put some valid, writable addresses in that thing, their values are not viable targets for dereference, and that includes targeting from something like `strcpy`. – WhozCraig Mar 03 '22 at 10:14
  • 2
    `strcpy(urls[index], url)` -> `urls[index] = strdup(url)`. [`Documentation for strdup`](https://en.cppreference.com/w/c/experimental/dynamic/strdup). If `strdup` is not available on your platform you can write your own (2-3 lines of code). – Jabberwocky Mar 03 '22 at 10:17

1 Answers1

0

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 */;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • @Peter-ReinstateMonica Not my downvote, but endless FAQ should be closed as duplicates, not answered for the purpose of grinding rep. – Lundin Mar 03 '22 at 10:29
  • @Peter-ReinstateMonica Not my DV., but maybe it was dvted because of the suggestion to have a 2 dimensional array. – Jabberwocky Mar 03 '22 at 10:29
  • @Jabberwocky Well, a 2D array seems like a very natural solution for a sequence of strings.-- At second thought it may have been downvoted for answering an obvious dup. – Peter - Reinstate Monica Mar 03 '22 at 10:34