我正在尝试 append 一个带有特定字符的字符串。我认为出现了段错误,因为我正在尝试 append 到内存地址,但我不知道如何更改它。
这是我调试时显示的错误,
print: 6
word to be appended: ����Z�����H���E
Segmentation fault (core dumped)
这是段错误对应的代码
void append(char* s, char c){
printf("print: 5\n");
int len = strlen(s);
printf("print: 6\n");
printf("word to be appended: %s\n", s);
s[len] = c;
printf("print: 7\n");
s[len+1] = '\0';
}
这就是对上面函数的调用,在这组代码的最底层加上了相应的变量初始化
int x;
char *tempLine = NULL;
char *token = NULL;
char *punctuationChar;
size_t length = 0;
int charCount = 0;
char *word;
int i;
int p;
int check = 0;
struct node *curr = NULL;
struct node *newNode = NULL;
(*head) = malloc(sizeof(struct node));
curr = (*head);
rewind(stream);
for(x = 0; x < size; x++){
getline(&tempLine, &length, stream);
token = strtok(tempLine, " ");
if(x == 0){
charCount = strlen(token);
curr -> word = malloc(charCount *(sizeof (char)) + 1);
strcpy(curr -> word, token);
token = strtok(NULL, " ");
}else{
while(token != "\n"){
check = 0;
printf("token: %s\n", token);
charCount = strlen(token);
printf("print: 1\n");
//check for punctuation aka, last word on line
for(i = 0; i < charCount; i++){
printf("iteration: %d\n", x);
if(ispunct(token[i])){
printf("print: 2\n");
append(punctuationChar, token[i]);
check = 1;
最佳答案
您调用append(punctuationChar, token[i])
,但 punctionatChar 尚未初始化。这会产生未定义的行为。
为了克服这个问题,让punctuationChar
指向一个正确分配的内存空间,该空间使用有效的字符串初始化,即带有字符串终止字符的字符串;
要尝试一下,您可以简单地从以下开始:
char tempBuffer[100] = "something to start with";
char* punctationChar = tempBuffer;
这不会解决程序流程中可能出现的问题;但它应该显示您问题的根本原因。
关于c - 段错误追加空字符串 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49870895/