私は基本的に文をとって、各単語が何回出現するのかを数えることができるCプログラムを作ることに取り組んでいます。私は、問題を正確に再現したバージョンを削除しました。このCプログラムはなぜこの場所でセグメンテーションしていますか?
#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);
}
としてだけでなく、実行からの出力:
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? */
グロー機能を終了するとの間でループを言葉[0]の値を再行く理由を私は理解していませんよ - > strは突然失われます。私は行方不明のものがありますか?
[私は私がまた私のメソッドのプロトタイプが正しいものではありません実現malloc.I何かを解放する必要があることを知っていますが、私はちょうど私の問題を実証した迅速なプログラムを作りたいと思っ]
ヒント:何がします ' void f(int i){i = 7;} int main(){int x = 5; f(x) printf( "%d \ n"、x); return 0;} 'print? 'int i'を' word ** words'に、 'int x'を' word ** words'に、 '7'を' realloc(...) 'に変更してください。 – immibis
もう一つの間違いは、間違った "文字列"の割り当てでは、文字列の長さは 'strlen(str)+ 1'で、NUL終端文字を考慮に入れます。 –
あなたの例では、値が渡されてから5が出力されます。単語**を渡すとそれはポインタになりませんので、変更はメインにも反映されますか? これをキャッチしてくれてありがとうJean!私の悪い、私はその変更を反映するように編集しました。 – Nateb1121