少し前にこのサイトで関数を見ました。
getc と stdin を使用して文字列を取得し、文字列を格納するために必要なだけのメモリを正確に割り当てる関数です。次に、上記の文字列で満たされた割り当てられたメモリへのポインタを返します。
私の質問は、この関数に (割り当てられたメモリを後で手動で解放する必要がある以外に) 欠点はありますか? それを改善するためにあなたは何をしますか?
char *getstr(void)
{
char *str = NULL, *tmp = NULL;
int ch = -1, sz = 0, pt = 0;
while(ch)
{
ch = getc(stdin);
if (ch == EOF || ch == 0x0A || ch == 0x0D) ch = 0;
if (sz <= pt)
{
sz++;
tmp = realloc(str, sz * sizeof(char));
if(!tmp) return NULL;
str = tmp;
}
str[pt++] = ch;
}
return str;
}
ここであなたの提案を使用した後、更新されたコードです。この関数はユーザー入力に使用されているため、バッファーに 256 バイトを使用することにしました。
char *getstr(void)
{
char *str, *tmp = NULL;
int ch = -1, bff = 256, pt = 0;
str = malloc(bff);
if(!str)
{
printf(\nError! Memory allocation failed!");
return 0x00;
}
while(ch)
{
ch = getc(stdin);
if (ch == EOF || ch == '\n' || ch == '\r') ch = 0;
if (bff <= pt)
{
bff += 256;
tmp = realloc(str, bff);
if(!tmp)
{
free(str);
printf("\nError! Memory allocation failed!");
return 0x00;
}
str = tmp;
}
str[pt++] = ch;
}
tmp = realloc(str, pt);
if(!tmp)
{
free(str);
printf("\nError! Memory allocation failed!");
return 0x00;
}
str = tmp;
return str;
}