gpt4 book ai didi

c - 段错误:11 in C

转载 作者:行者123 更新时间:2023-11-30 19:12:56 24 4
gpt4 key购买 nike

我正在用 C 语言编写一个程序,用字符串替换 char* 中名为“template”的数字,但我不断收到 Segmentation Failure: 11 错误。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

char *rep_str(const char *s, const char *old, const char *new1){
char *ret;
int i, count = 0;
int newlen = strlen(new1);
int oldlen = strlen(old);

for (i = 0; s[i] != '\0'; i++){
if (strstr(&s[i], old) == &s[i]){
count++;
i += oldlen - 1;
}
}
ret = (char*)malloc(i + count * (newlen - oldlen));
if (ret == NULL)
exit(EXIT_FAILURE);
i = 0;
while (*s){
if (strstr(s, old) == s){ //compare the substring with the newstring
strcpy(&ret[i], new1);
i += newlen; //adding newlength to the new string
s += oldlen;//adding the same old length the old string
} else {
ret[i++] = *s++;
}
}
ret[i] = '\0';

return ret;
}

char* madlib_by_numbers(char* temp, int word_count, char* words[]){
char* numbers[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
int tempSize = strlen(temp);

for (int i = 0; i < tempSize; i++){
if (isdigit(temp[i])){
for (int j = 0; j < (sizeof(numbers) / sizeof(char*)); j++){
temp = rep_str(temp, numbers[j], words[j]); //it makes it to this line, but never gets to assert()
}
}
}

return temp;
}

int main() {
char* temp1 = "The 1 0 likes to 2 in the moonlight.";
char* words[] = {"git", "brilliant", "swim"};
char* result = "The brilliant git likes to swim in the moonlight.";
int stringLength = strlen(result);

char* test = madlib_by_numbers(temp1, 3, words);
assert(strncmp(test, result, stringLength) == 0);
free(test);

return 0;
}

当我运行调试器时,它只是说:Segmentation Fault: 11

我只是想了解段错误是从哪里来的,我怀疑我的一个循环运行了太多次。

最佳答案

您的代码存在一些问题。但是,您问题的直接答案就在这个循环中:

for (int j = 0; j < (sizeof(numbers) / sizeof(char*)); j++){
temp = rep_str(temp, numbers[j], words[j]);
}

您正在为每个数字调用 rep_str,而您的意思是仅当 temp 中的数字与 中的相应数字匹配时才调用 rep_str数字。因此,请在 temp=... 行之前添加条件 if(strcmp(temp,numbers[j]) == 0)。那么它就会解决你当前的问题。

出现段错误的原因是 words 数组中只有三个元素。您的旧循环索引从 0 到 9,并在 j=3 超出范围时失败。

此外,删除程序末尾的free()test 从未分配,将导致核心转储。

关于c - 段错误:11 in C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36273875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com