Функция realloc вызывает Ошибку сегментирования
В функции fill_text() realloc'ом расширяю text (указатель на массив структур). Но realloc() здесь выдает ошибку (в функции fill_sent функция работает нормально). В чем может быть проблема? (принудительное приведение типа не помогает)
,
#include <stdio.h>
#include <stdlib.h>
struct Sentence{
char* string;
int len;
};
int fill_sent(struct Sentence* sent){
int i = 0, nl_counter = 0;
char c;
sent->string = (char*)malloc(3 * sizeof(char));
while( (c = getchar()) != '.' && c != '?' && c != '!'){
sent->string[i] = c;
if(c == '\n'){
nl_counter++;
if (nl_counter == 2)
return 0;
}
++i;
sent->string = realloc(sent->string, (i + 3) * sizeof(char));
}
sent->string[i] = '.';
sent->string[i + 1] = '\0';
sent->len = i + 1;
return 1;
}
int fill_text(struct Sentence *text){
int i = 0;
while(fill_sent(&text[i])){
i++;
text = realloc(text, sizeof(struct Sentence) * (i + 1));
}
return i;
}
void print_text(struct Sentence *text, int len){
for(int i = 0; i < len; ++i){
printf("\n%s\n", text[i].string);
}
}
int main(){
struct Sentence* text = malloc(sizeof(struct Sentence));
int len = fill_text(text);
print_text(text, len);
}
Ответы (1 шт):
Автор решения: AlexGlebe
→ Ссылка
В функции
int fill_text(struct Sentence *text){
int i = 0;
while(fill_sent(&text[i])){
i++;
text = realloc(text, sizeof(struct Sentence) * (i + 1));
}
return i;
}
вы выделенную память храните в локальной переменной. И меняете указатель локально. А функция main не знает, что переданный указатель уже неликвидный.
Передавать указатель надо по-указателю :
main :
int len = fill_text( & text);
fill_text :
int fill_text(struct Sentence * * text){
int i = 0;
while(fill_sent(&(*text)[i])){
i++;
* text = realloc( * text, sizeof(struct Sentence) * (i + 1));
}
return i;
}