【问题标题】:Allocate memory to dynamically growing char array in C throws segmentation fault在 C 中为动态增长的 char 数组分配内存会引发分段错误
【发布时间】:2021-09-19 10:07:10
【问题描述】:

我在 C 中创建了一个自定义类型(类型 def),一个动态 char 数组,但是当我尝试使用 malloc 初始化此类型 def 时收到分段错误错误。以下代码是我的结构及其实现的代码sn-p:

#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;
}

【问题讨论】:

  • 不完整的代码 sn-ps 是不够的。请提供complete minimal reproducible example
  • 另外,做基本的调试。在调试器中运行您的程序。这将为您提供触发段错误的确切代码行等等。
  • 对不起,我会解决这个问题,1 秒...
  • 这仍然不是一个完整的例子。请阅读链接。我们需要任何人都可以完全按照所示复制的代码来运行并查看问题。
  • 我编辑了,代码有点贵,我试图缩小

标签: c segmentation-fault char malloc dynamic-memory-allocation


【解决方案1】:
struct Lexer {
  CharList * text;
  int position;
  char currentChar;
};

你没有分配CharList * text;;最简单的解决方法是:

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

【讨论】:

  • 谢谢,这解决了我的问题,但你能解释一下为什么吗?我不明白为什么只是删除指针就解决了所有问题
猜你喜欢
  • 2013-05-27
  • 1970-01-01
  • 2015-08-09
  • 1970-01-01
  • 1970-01-01
  • 2015-09-25
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
相关资源
最近更新 更多