[英]Extra byte when creating dynamic string
我已經編寫了一個程序來使用realloc()
進行輸入並動態分配內存,但是似乎出現了錯誤,因為如果我按char打印最終的字符串char我似乎在末尾有2個空字節,我確定這是會變得很愚蠢,但是我花了一些時間試圖找出原因,但失敗了,所以希望在這里學習一些東西。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int count = 0;
char *str;
char tmp;
str = malloc(sizeof(char));
while (tmp != '\n') {
tmp = getchar();
str = realloc(str, (count + 1) * sizeof(char));
*(str + count) = tmp;
count += 1;
}
*(str + count) = '\0';
puts(str);
// This is just to try and see what was happening
for (int i = 0; i <= count; i++)
printf("str[%d] = %c\n", i, str[i]);
free(str);
str = NULL;
return EXIT_SUCCESS;
}
這個循環至少應該看起來像
for(int i = 0; i < count; i++)
^^^
printf("str[%d] = %c\n", i, str[i]);
否則寫會更好
for(int i = 0; str[i]; i++)
printf("str[%d] = %c\n", i, str[i]);
要么
int i = 0;
for ( char *p = str; *p; ++p )
printf( "str[%d] = %c\n", i++, *p );
並更改這些語句
while(tmp != '\n') {
tmp = getchar();
至
while ( ( tmp = getchar() ) != EOF && tmp != '\n' )
也可以代替此語句更安全
str = realloc(str, (count + 0x01) * sizeof(char));
來寫
char *p = realloc(str, (count + 0x01) * sizeof(char));
if ( !p ) break;
else str = p;
這里要提到四件事。
while(tmp != '\\n')
正在讀取未初始化的自動局部變量值而不進行初始化。 它調用未定義的行為 。
str = realloc(str, (count + 0x01) * sizeof(char));
非常糟糕,如果realloc()
失敗,您也會丟失實際的指針。 始終使用臨時指針來保存realloc()
的返回值,並在進行正確的錯誤檢查之后,將其分配回主指針。
sizeof(char)
保證為1
。 您無需用作乘法器。 這是多余的。
for
循環條件應為i < count
否則,您將遇到一一錯誤。 C
使用基於0的索引。
那就是
realloc()
返回值是否成功以及函數族是否成功。 getchar()
返回一個int
。 您應該將tmp
的類型更改為int tmp = 0;
除了未初始化的變量訪問,兩個“空字符”是:
換行符,因為您在讀取和存儲下一個字符之前先檢查\\n
,並且
未初始化內存中的字符,因為您在i <= count
而不是i < count
錯誤地循環。
使用for (;;)
(無限循環)並檢查if (tmp == '\\n') { break; }
if (tmp == '\\n') { break; }
緊跟在getchar()
以避免未初始化的變量訪問和結尾的換行符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.