Си. Почему возникает ошибка mremap_chunk(): invalid pointer
Логика программы: считывает введенный текст посимвольно в виде динамического массива предложений, сохраняя только уникальные предложения, а затем выводит каждое отдельное предложение. Как я понял такая ошибка возникает из-за неверно определенного указателя, хотя в моей программе вроде как все определено верно. Подскажите, пожалуйста, где ошибка?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wctype.h>
#include <wchar.h>
#include <locale.h>
#define MEM_STEP 5 * sizeof(wchar_t)
struct Text {
struct Sentence **text;
int size;
int n;
};
struct Sentence {
wchar_t *str;
int size;
};
struct Sentence *read_sentence(){
int size = MEM_STEP;
wchar_t *buf = (wchar_t*)malloc(size * sizeof(wchar_t));
wchar_t temp = getwchar();
int n = 0;
do{
if (n >= size - 8) {
wchar_t *buf = realloc(buf, (size + MEM_STEP) * sizeof(wchar_t));
size += MEM_STEP;
}
buf[n] = temp;
temp = getwchar();
n++;
}while (temp != '.' && temp != '\n');
buf[n] = temp;
buf[n + 1] = '\0';
if (buf[0] == '\n') {
buf++;
}
struct Sentence *sentence = malloc(sizeof(struct Sentence));
sentence->str = buf;
sentence->size = size;
return sentence;
}
int is_sent_unique(struct Sentence** txt, struct Sentence* sent, int n){
for(int i = 0; i < n; i++){
int k = 0;
for(int j = 0; j < wcslen(sent->str); j++){
if (towupper(txt[i]->str[j]) == towupper(sent->str[j]))
k++;
}
if(k == wcslen(sent->str) && k == wcslen(txt[i]->str))
return 0;
}
return 1;
}
struct Text read_text(){
int size = MEM_STEP;
struct Sentence **text = malloc(size * sizeof(struct Sentence*));
struct Sentence *temp;
int n = 0;
int nlcount = 0;
do{
temp = read_sentence();
if (n >= size - 2 * sizeof(struct String*)) {
struct Sentence **text = realloc(text, (size + MEM_STEP)* sizeof(struct Sentence *));
size += MEM_STEP;
}
if(temp->str[0] == '\n' && temp->str[1] == '\0'){
nlcount++;
}else{
while (temp->str[0] == '\t' || temp->str[0] == ' ' || temp->str[0] == '\n') {
temp->str++;
}
if (is_sent_unique(text, temp, n)){
text[n] = temp;
n++;
}
nlcount = 0;
}
}while (nlcount < 2);
struct Text txt;
txt.text = text;
txt.size = size;
txt.n = n;
return txt;
}
int main()
{
setlocale(LC_ALL, "");
int func_numb = 0;
struct Text main_text = read_text();
for (int i = 0; i < main_text.n; i++) {
wprintf(L"%s\n", main_text.text[i]->str);
}
printf("Количество предложений %d", main_text.n);
for (int i = 0; i < main_text.size; i++) {
free(main_text.text[i]);
}
free(main_text.text);
return 0;
}