Home > Net >  Initializing two dimensional string dynamic array and passing by reference
Initializing two dimensional string dynamic array and passing by reference

Time:11-18

I am trying to learn C pointer passing. So please forgive my ignorance.

I want to allocate a 2 dimensional dynamically allocated string array in a function. The function signature is void so the parameters are by reference.

The test file contains these two lines.

I am testing.
This is not an empty file.

Here is what I have done so far.

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void read_lines(FILE *fp, char** lines, int *num_lines) {
  ssize_t read;
  char * line = NULL;
  size_t len = 0;
  *num_lines = 0;


  while ((read = getline(&line, &len, fp)) != -1) {
    if (*num_lines == 0) {
      // For the first time it holds only one char pointer
      *lines = malloc(sizeof(char *));
    } else {
      // Every time a line is read, space for next pointer is allocated
      *lines = realloc(*lines, (*num_lines) * sizeof(char *));
    }
    // allocate space where the current line can be stored
    *(lines   (*num_lines)) = malloc(len * sizeof(char));
    // Copy data
    strcpy(*(lines   (*num_lines)), line);
    printf("Retrieved line of length %zu:\n", read);
    printf("%s\n", line);
    (*num_lines)  ;
    // After first line subsequent lines get truncated if I free
    // the storage here, then subsequent lines are not read completely
    //if (line) {
    //  free(line);
    //}
  }  
  if (line) {
    free(line);
  }

}
int main(void)
{
    FILE * fp;
    char *array;
    int num_lines;
    fp = fopen("file.txt", "r");
    if (fp == NULL)
        exit(EXIT_FAILURE);
    read_lines(fp, &array, &num_lines);
    printf("After returning\n");
    // Intend to access as array[0], array[1] etc
    // That's not working
    // If I access this way then I get seg violation after first line
    printf("%s\n", &array[0]);
    fclose(fp);
}

My questions are inline with code:

  • Why can't I free storage for line inside the while loop?
  • How do I access returned 2D array in main? array[0] array[1] doesn't seem to work? I want to do something similar.
  • Why seg fault is generated for the way I am doing it now?

Corrected code will help me understand. Also any good reference anybody can provide to get these concept clarified for C will be greatly appreciated.

CodePudding user response:

If you free(line) inside the while loop, you have to reset line to NULL and len to 0, before the next calling of getline. Otherwise, getline will think line is a valid buffer of size len, and may try to write to it, which is actually a so called "dangling pointer" now.

In the realloc line, the size should be (*num_lines 1) * sizeof(char *), one more element need to be allocate to hold the just read line.

And the array variable is char*, its address is taken and assiged to the parameter lines of read_lines. So lines is the address of array, and *lines is just array itself.

But

// allocate `char*[1]`
*lines = malloc(sizeof(char *));

and

// allocate `char*[N]` with N=`*num_lines`
*lines = realloc(*lines, (*num_lines) * sizeof(char *));

You assigned a char*[] to array, which is a char* in fact.

So, if you want your function return a array of strings (that is char*[] or char**) by parameter, you have to make the parameter a pointer to a array of strings (that is char***).

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

void read_lines(FILE * fp, char*** lines, int* num_lines) {
    ssize_t read;
    char* buffer = NULL;
    size_t buffer_len = 0;
    *num_lines = 0;

    while ((read = getline(&buffer, &buffer_len, fp)) != -1) {
        // `*lines` is actually `array`,
        // modify `*lines` will effectively modify `array`
        if (*num_lines == 0) {
            // `array` now is `char*[1]`
            *lines = (char**)malloc(sizeof(char*)); // A
        }
        else {
            // `array` now is `char*[(*num_lines)   1]`
            *lines = (char**)realloc(*lines, (*num_lines   1) * sizeof(char*)); // B
        }

        // *(x n) is the same as x[n], this line is actually doing:
        // `array[*num_lines] = malloc...
        *(*lines   (*num_lines)) = (char*)malloc((read   1) * sizeof(char)); // C
        strcpy(*(*lines   (*num_lines)), buffer);
        (*num_lines)  ;

        printf("Retrieved line of length %zu:\n", read);
        printf("%s\n", buffer);
    }
    if (buffer) {
        // `line` is `malloc`ed or `realloc`ed by `getline`,
        // have to be `free`ed
        free(buffer);
    }
}
int main(void)
{
    FILE* fp;
    char** array;
    int num_lines;
    fp = fopen("file.txt", "r");
    if (fp == NULL)
        exit(EXIT_FAILURE);
    read_lines(fp, &array, &num_lines);
    printf("After returning\n");
    for (int i = 0; i < *num_lines; i  ) {
        printf("%s\n", array[i]);
        free(array[i]); // corresponding to C
    }
    free(array); // corresponding to A or B
    fclose(fp);
}
  • Related