前段時間我在這個網站上看到了一個功能,那就是我爲了我的使用而做了一些調整。這種字符串檢索方法的任何缺點?
這是一個函數,它使用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;
}
提醒我這一個:http://stackoverflow.com/a/8164021/714501 – cnicutar
是的!這正是我第一次看到這個功能的地方。 –
您的修訂版本更合理。你可能也想考慮爲每個realloc()乘以2,並在他的回答的評論中看到Qnan和我之間的討論。雖然如你所說,這只是手動用戶輸入,你有什麼是好的。 – delicateLatticeworkFever