Ich schreibe ein Programm in C, das eine Zahl in einem char * namens "Vorlage" durch eine Zeichenfolge ersetzt, aber ich bekomme ständig eine Segmentation Fault: 11 Fehler.Segmentation Fault: 11 in C
#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;
}
und als ich den Debugger ausführen, heißt es einfach: Segmentation Fault: 11
Was ich möchte nur verstehen, wo die Segmentation fault Fehler herkommt, habe ich den Verdacht einer meiner Schleifen zu läuft viele Male.
Aber wo ist Ihr 'main()' Funktion? –
** Woher ** erhalten Sie diesen Fehler? Was sagt der Debugger? – Olaf
@Olaf macht es zu "temp = rep_str (temp, Zahlen [j], Wörter [j])" und ich bekomme das korrekte Ergebnis, aber dann bekomme ich den Segmentation Fault Fehler und es macht es niemals zu assert() in mein Haupt. – Teecolz