1

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;
}
7
  • Incomplete code snippets are not enough. Please provide a complete minimal reproducible example. Commented Jul 9, 2021 at 1:12
  • Also, do basic debugging. Run your program in a debugger. That will give you the exact line of code that triggers the seg fault and more. Commented Jul 9, 2021 at 1:13
  • 1
    Sorry, I will fix the question, 1 sec... Commented Jul 9, 2021 at 1:13
  • That is still not a complete example. Please read the link. We need to have code that anyone can copy exactly as shown to run and see the problem. Commented Jul 9, 2021 at 1:20
  • 1
    i edited, the code is a little bit expensive and i have tried to minify Commented Jul 9, 2021 at 1:37

1 Answer 1

1
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;
};
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, this solved my problem, but you could explain me why? I did not understand why just removing the pointer has fixed all

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.