-2

I am trying to input a list of strings. The list may vary in length, so I try to use dynamic allocation. Each string has 20 chars max. The list ends with a single dot. I have been working on it for some time now, but I keep getting a segmentation fault and I am not sure why. I guess the error is in my use of realloc / malloc, but I just cannot see what exactly I am doing wrong. The code block is part of a larger program, but I singled out this block and am trying to make it work. It works fine for a "list" of one word followed by a dot. As soon as I try to read a list of two or more strings, I get the segmentation error. Any help would be great, thanks!

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

char **resizeDynamicArray(char **arr, int newSize){
  char **ptr = realloc(arr, newSize*sizeof(char*)); 
  if (ptr==NULL) {
    printf("Error: memory allocation failed.\n"); 
    exit(-1); 
  }
  return ptr; 
}

int input (char ***seq){
  int len = 0; 
  char string[21]; 
  *seq=NULL;

  do{
    scanf("%s", string); 
    if (string[0] != '.'){
      *seq = resizeDynamicArray(*seq, (len+1)); 
      *seq[len] = malloc(sizeof(char[21]));
      strcpy((*seq)[len], string); 
      len++; 
    }
  } while (string[0] != '.');
  return len; 
}

int main(int argc, char *argv[]) {
  int length;
  char **words; 

  length = input(&words); 
  for (int i=0; i<length; ++i){
    printf("%s\n", words[i]); 
  } 
  for (int i=0; i<length; ++i){
    free(words[i]); 
  }  
  free(words); 
  return 0;
}
Neutrino
  • 46
  • 7

1 Answers1

1

Change the following line:

*seq[len] = malloc(sizeof(char[21]));

to:

(*seq)[len] = malloc(sizeof(char[21]));

There is an extra level of indirection that needs to be dereferenced before you can index into the top-level array.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41