Home > database >  Memory allocation for strings of array
Memory allocation for strings of array

Time:12-15

I need to parse csv file. I create array of strings and allocating memory for that The first cycle while(fgets(line,100,fp) is succesful, but when it enters the second the values are overwritten by the data of line

while (fgets(line, 100, fp))
{
    num_of_string  ;
    code = (char **)realloc(code, sizeof(char *) * (num_of_string));
    occupation = (char **)realloc(occupation, sizeof(char *) * (num_of_string));
    num_of_ppl = (char **)realloc(num_of_ppl, sizeof(char *) * (num_of_string));
    
    char * column = strtok(line, ",");
    code[num_of_string-1] = malloc(sizeof(char) * (strlen(column) 1));
    code[num_of_string-1] = column;
    counter  ;
    while (column)
    {
        if (counter == 1)
        {
            column = strtok(NULL, "\"");
            occupation[num_of_string-1] = malloc(sizeof(char) * (strlen(column) 1));
            occupation[num_of_string-1] = column;
            counter  ;
            column = strtok(NULL, ",");
        } else if (counter == 2) {
            num_of_ppl[num_of_string-1] = malloc(sizeof(char) * (strlen(column) 1));
            num_of_ppl[num_of_string-1] = column;
            counter  ;
            column = strtok(NULL, ",");
        } else {
            column = strtok(NULL, ",");
            counter  ;
        }
    }
    counter = 0;
}

CodePudding user response:

Error is here:

code[num_of_string-1] = malloc(sizeof(char) * (strlen(column) 1));
code[num_of_string-1] = column;

The second assignment overwrites the dedicated allocated block with a pointer to data pointed by column. And those data are overwritten whenever a new line is parsed.

I suggest using strdup() to allocate a buffer and make a copy of the string.

Just replace the two lines above with:

code[num_of_string-1] = strdup(column);

There are similar errors for arrays occupation and num_of_pll.

CodePudding user response:

            column = strtok(NULL, "\"");
            occupation[num_of_string-1] = malloc(sizeof(char) * (strlen(column) 1));
            occupation[num_of_string-1] = column;

Pointer column points into your buffer line that is common for all lines you read from the file. You allocate memory for the token but then you assign column creating a memory leak as you cannot free the allocated memory any longer. By assigning pointers into the same buffer to all your array entries you will spoil old entries.

That is not how copying a string works. You need to use strcpy instead:

            column = strtok(NULL, "\"");
            occupation[num_of_string-1] = malloc(sizeof(char) * (strlen(column) 1));
            strcpy(occupation[num_of_string-1], column);

You should also check every return value for NULL pointers.

  • Related