将内存分配给 C 中动态增长的 char 数组会抛出分段错误
Allocate memory to dynamically growing char array in C throws segmentation fault
我在 C 中创建了一个自定义类型(type def),一个动态字符数组,但是当我尝试使用 malloc 初始化此类型 def 时收到分段错误。以下代码是我的结构及其实现的代码片段:
#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] : '[=10=]');
}
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;
}
struct Lexer {
CharList * text;
int position;
char currentChar;
};
你没有分配CharList * text;
;最简单的修复是:
struct Lexer {
CharList text;
int position;
char currentChar;
};
我在 C 中创建了一个自定义类型(type def),一个动态字符数组,但是当我尝试使用 malloc 初始化此类型 def 时收到分段错误。以下代码是我的结构及其实现的代码片段:
#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] : '[=10=]');
}
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;
}
struct Lexer {
CharList * text;
int position;
char currentChar;
};
你没有分配CharList * text;
;最简单的修复是:
struct Lexer {
CharList text;
int position;
char currentChar;
};