José Thomaz
José Thomaz

Reputation: 53

Allocate memory to dynamically growing char array in C throws segmentation fault

I have created a custom type (type def) in C,a dynamic char array, but I receive the segmentation fault error when I try to initialize this type def using malloc. The following code is a code snippet of my structure and its implementation:

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

typedef struct {
  char * list;
  size_t used;
  size_t size;
} CharList;

void initCharList(CharList *l) {
  size_t initialSize = 10;
  l->list = (char*)malloc(10+1 * sizeof(char)); 
  l->used = 0;
  l->size = initialSize;
}

void appendStringCharList(CharList *l, char elements[], int arr_length) {
  if (l->used + arr_length >= l->size) {
    l->size += arr_length;
    l->list = realloc(l->list, l->size * sizeof(char *));
  }
  for (int i = 0; i < arr_length; i++) {
    l->list[l->used++] = elements[i];
  }
}

struct Lexer {
  CharList * text;
  int position;
  char currentChar;
};

void advanceLexer(struct Lexer * lexer) {
  lexer->position +=1;
  lexer->currentChar = (char) ((lexer->position < lexer->text->used) ? lexer->text->list[lexer->position] : '\0');
}

void createLexer(struct Lexer * lexer, char text[], int arrLength) {
  initCharList(lexer->text);
  appendStringCharList(lexer->text, text, arrLength);
  lexer->position = -1;
  advanceLexer(lexer);
}

int main(void) {
  struct Lexer lexer;
  char myCharArr[] = "1234567890";
  createLexer(&lexer, myCharArr, 11);
  return 0;
}

Upvotes: 1

Views: 68

Answers (1)

Ken Y-N
Ken Y-N

Reputation: 15009

struct Lexer {
  CharList * text;
  int position;
  char currentChar;
};

You do not allocate CharList * text;; the simplest fix is:

struct Lexer {
  CharList text;
  int position;
  char currentChar;
};

Upvotes: 1

Related Questions