realloc地址重用问题,当输入大于5行时候,就会重用分配地址,但是旧数据全部清空了

#define STDC_WANT_LIB_EXT1 1
#include
#include
#include
#include
#define BUF_LEN 101
#define COUNT 5

int main()
{
char buf[BUF_LEN];
size_t str_count = 0;
size_t capacity = COUNT;
char **pS = calloc(capacity, sizeof(char*));
//char **psTemp = NULL;
char pTemp = NULL;
size_t str_len = 0;
FILE *pfile = NULL;
char *filename = "C:\Users\Administrator\Desktop\mystyle.txt";
bool sorted = false;
char fstring[BUF_LEN] = "cccbbbaaaa\naaabbbcccc\nbaccbasadd\nbaccbasada\nbbbbbbbbbbb\n";
printf_s("Enter strings to be sorted, one per line ."
"Press Enter to end:\n");
//Read in all the strings
if (fopen_s(&pfile, filename, "w"))
{
printf_s("Error to open file.\n");
exit(1);
}
fputs(fstring,pfile);
fclose(pfile);
if (fopen_s(&pfile, filename, "r"))
{
printf_s("Error to open file.\n");
exit(1);
}
char *ptr = (char
)calloc(BUF_LEN, sizeof(char));
setvbuf(pfile, NULL, _IOFBF, BUFSIZ);
while (true)
{
buf[0] = '\n';
fgets(buf, BUF_LEN, pfile);
ptr = buf;
if (!ptr)
{
printf_s("Error reading string.\n");
free(pS);
pS = NULL;
return 1;
}
if (*ptr == '\n')break;
//printf_s("buf=%s", buf);
if (str_count == capacity)
{
printf_s("str_count=%zd\ncapacity=%zd\n", str_count, capacity);
capacity += capacity / 4;
printf_s("1111111111%s\n", pS[1]);//调试
char **psTemp = realloc(pS, capacity);
if (!psTemp)
{
printf_s("Error memory.\n");
return 1;
}
pS = psTemp;
printf_s("2222222222%s\n", psTemp[1]);//调试
free(psTemp);
psTemp = NULL;
}
str_len = strnlen_s(buf, BUF_LEN) + 1;
if (!(pS[str_count] = malloc(str_len)))
return 2;
strcpy_s(pS[str_count++], str_len, buf);
printf_s("pS[%zd]=%s", str_count - 1, pS[str_count-1]);
}
//printf_s("str_count=%zd\ncapacity=%zd\n", str_count, capacity);
while (!sorted)
{
sorted = true;
for (size_t i = 0; i < str_count - 1; i++)
{
if (strcmp(pS[i], pS[i + 1])>0)
{
sorted = false;
pTemp = pS[i];
pS[i] = pS[i + 1];
pS[i + 1] = pTemp;
}
}
}
printf_s("\n\nyour input sorted in ascending sequence is:\n");
for (size_t i = 0; i < str_count; i++)
{
printf_s("pS[%zd]=%s",i, pS[i]);
free(pS[i]);
pS[i] = NULL;
}
free(pS);
pS = NULL;
fclose(pfile);
pfile = NULL;
return 0;
}

个人觉得不理解的地方