Temelde bir cümleyi alıp her kelime içinde kaç kere göründüğü sayabilir bir C programı yapmaya çalışıyorum. Sorunu tam olarak yeniden üreten soyulmuş bir sürüm oluşturdum.Bu C programı neden bu konumda segfaultedir?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct testStrut{
char * string;
int uses;
}word;
void grow();
int main(){
int i;
int count = 1;
word ** words;
words = (word **) malloc(count * sizeof(word *));
words[0] = (word *) malloc(sizeof(word));
for(i = 0; i < 10; i++){
printf("Re-looping i: %d \n", i);
printf("words[0]->string = %s \n", words[0]->string);
grow("TEST", words, &count);
}
printf("Done.");
return 0;
}
void grow(char * str, word ** words, int * count){
word ** tmp;
tmp = realloc(words, (*count) * sizeof(word *));
if(tmp){
tmp[(*count)-1] = malloc(sizeof(word));
tmp[(*count)-1]->string = malloc(strlen(str)+1); /*+1 for null terminator as pointed out */
strcpy(tmp[(*count)-1]->string, str);
tmp[(*count)-1]->uses = 1;
words = tmp;
(*count)++;
} else{
printf("Failure to allocate. \n");
exit(0);
}
printf("Count: %d and word[0] %s \n", (*count), str);
}
yanı sıra bir çalışma çıktısı:
Re-looping i: 0
words[0]->string = (null)
Count: 2 and word[0] TEST
Re-looping i: 1
words[0]->string = TEST
Count: 3 and word[0] TEST
Re-looping i: 2
words[0]->string = TEST
Count: 4 and word[0] TEST
Re-looping i: 3
words[0]->string = TEST
Count: 5 and word[0] TEST /*Prints it fine? */
Re-looping i: 4
Segmentation fault (core dumped) /*Suddenly unable to print it? */
Yetiştirme fonksiyonunu sona erdiren ve arasındaki döngü içinde kelime [0] değerini yeniden gidiş neden anlayamıyorum -> str aniden kayboldu. Kaybettiğim bir şey mi var?
[Ben de benim yöntemi prototip doğru biri değil fark malloc.I şey azat gerektiğini biliyoruz ama sadece benim sorunu göstermiştir hızlı bir program yapmak istediğini] İlk olarak
İpucu: ne işe yarar ' void f (int i) {i = 7;} int main() {int x = 5; f (x); printf ("% d \ n", x); 0;} 'yazdır? Şimdi realloc (...) '' üzere 7 ' 'değiştirmek kelime ** words'' etmek I' int ve 'int x' kelimesine' için ** words' ve' – immibis
Başka bir hata bir yaptık ki yanlış "dize" ayırma, bir dizenin uzunluğu, NUL sonlandırma karakterini hesaba katmak için strlen (str) + 1 'dir. I değeri tarafından geçirilen çünkü haber iletir zaman değil, –
Kişisel Örnek baskılar 5 ** kelime bu yüzden herhangi bir değişiklik de ana olarak yansıtılacak bir işaretçi? Bunu yakalamak için Jean'e teşekkürler! Kötüyüm, bu değişikliği yansıtacak şekilde düzenledim. – Nateb1121