Home > Enterprise >  Issue allocating memory for dynamic array of structs in C
Issue allocating memory for dynamic array of structs in C

Time:11-18

I am trying to dynamically allocate memory for an array of structs

I scan in input from files given in the command line into a struct which contains information on the position of each url in the file.

file1.txt
url4
url3
url2
url1
url5

file2.txt
url3
url2
url1
url4
typedef struct url {
    char *url;  // url
    int pos;    // position in original file
} URL;

int main(int argc, char *argv[]) {
    //Error when no file in given in commandline
    if (argc < 2) {
        fprintf(stderr, "Usage: %s rankA.txt  rankD.txt", argv[0]);
        exit(1);
    }

    URL *urlArray = NULL;
    char url[1000];

    for (int i = 0; i < argc - 1; i  ) {
        FILE *fp = fopen(argv[i   1], "r");
        int numURLs = 0;

        while (fscanf(fp, "%s", url) != EOF) {
            urlArray = realloc(urlArray, (numURLs   1) * sizeof(struct url));
            urlArray[i].url = malloc(strlen(url)   1);
            strcpy(urlArray[numURLs  ].url, url);
            urlArray->pos = numURLs;
        }

        fclose(fp);
    }

    return 0;
}

when I run this code i get "SEGV on unknown address" error. I know I've gone wrong somewhere when allocating memory I just can't figure out where. How would I fix this?

CodePudding user response:

urlArray = realloc(urlArray, (numURLs   1) * sizeof(struct url));
urlArray[i].url = malloc(strlen(url)   1);

You're using the variable i when you should be using numURLs. i is the loop variable, which is why you're getting the same URL in every spot.

Change those lines to this and it should work:

urlArray = realloc(urlArray, (numURLs   1) * sizeof(struct url));
urlArray[numURLs].url = malloc(strlen(url)   1);
  • Related