Home > OS >  Why is not correct the way I'm using my dynamic array of strings?
Why is not correct the way I'm using my dynamic array of strings?

Time:09-23

I've a .log file. In this file there are many lines. All I want to do is to read each single line and put it into a dynamic array of string:

   char **all_samples = malloc(sizeof(char));

    int i=0; 

    while ((read = getline(&line, &len, fp)) != -1)
    {
        if (strstr(line, slave) != NULL)
        {
            all_samples[i] = malloc(sizeof(*line)*len 1);
            all_samples[i] = line;
            line = NULL;
            i  ;

        }

    }

What happens is that the array only contains about 20 strings, and after this number I have a segmentation fault. Thanks to the i index, I know that the number of strings the array should contain is 32. What am I doing wrong? The error is in the memory allocation? Where is the problem? Can you please explaine me also theorically what I am doing wrong?

CodePudding user response:

See how you go with this:
(No responsibility taken for unseen code.)

#define MAX_SLAVES (32)

// Get a pointer to heap array of 32 pointers to char (ie: strings)
// calloc() used because region is init'd to 0's
char **all_samples = calloc( MAX_SLAVES, sizeof *all_samples );
/* omitting test for NULL */

int i=0; 

// No experience with 'getline()'. 'fgets()' would be portable
while ((read = getline(&line, &len, fp)) != -1)
{
    if (strstr(line, slave) != NULL && i < MAX_SLAVES ) // VERY important!
    {
        all_samples[i] = malloc( strlen( line )   1 );
        /* omitting test for NULL */

        strcpy( all_samples[i], line );
        i  ;
        // line = NULL; // is this necessary???
    }
}
  • Related