Search code examples
cdynamic-arrays

How to correctly implement a dynamic array in C


I have tried to write a short program in C that takes in space separated tokens from stdin, shuffles (permutes) the tokens and then prints the shuffles tokens to stdout. My shuffling algorithm works fine, the problem lies in the token parsing. I wanted to store the tokens in a dynamic string array so the program could support any number of tokens to be passed in through stdin. However, my current implementation of the dynamic array results in a segmentation fault whenever the array needs to be expanded. What am I doing incorrectly?

My Code:

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 33

int main(int argc, char* argv[]) {
  int i,j,k;
  i=j=k=0;
  int arrSize = 10;
  /* Temp fix */
  /* Get token count as command line argument */
  //if (argc==2) { sscanf(argv[1],"%d",&arrSize); }
  char  c='\0';
  char* t;
  char** datArr = (char**)malloc(sizeof(char*)*arrSize);
  //char* datArr[arrSize];
  char  token[BUFFERSIZE];
  while ( (c=getc(stdin)) != EOF && c != '\0') {
    if(isspace(c)) {
      token[i] = '\0';
      i=0;
      if ( j >= arrSize) {
        arrSize *= 2;
        realloc(datArr, arrSize);
      }
      char* s = (char*)malloc(sizeof(char[BUFFERSIZE]));
      strcpy(s,token);
      datArr[j++] = s;
    }
    else if(i+1 < BUFFERSIZE) {
      token[i++] = c;
    }
  }
  /* Permutate & Print */
  srand(time(NULL));
  for(i=0;i<j;++i) {
    k = rand()%(j-i);
    t = datArr[k];
    datArr[k] = datArr[j-i-1];
    datArr[j-i-1] = t;
  }
  for(i=0;i<j;++i) { printf("%s ",datArr[i]); }
  printf("\n");
  return 0;
}

NOTE: I know I did free the memory yet

Some sample input (to keep it card themed):

2C 3C 4C 5C 6C 7C 8C 9C 10C JC KC QC AC 2S 3S 4S 5S 6S 7S 8S 9S 10S JS KS QS AS

Solution

  • VaughnCato's comment on the original OP was the correct answer to the question.

    "You need to use datArr = (char**)realloc(datArr,arrSize*sizeof(char*));"

    Thanks VaughnCato!