C字符串是NUL終止,所以
char *maxCharac(int x)
{
char *str = malloc(x + 1);
if (str != NULL)
{
for (int i = 0; i < x; i++)
{
str[i] = 'a';
}
str[i] = '\0';
}
return str;
}
正如你可以看到:
- 您必須留有餘地,一個空終止
'\0'
malloc(x + 1);
sizeof(char)
永遠是1元的標準
- 您必須檢查
malloc&co
返回值!= NULL
使用前。
或者,以避免最後一條指令就可以使用calloc是歸零分配的內存
char *maxCharac(int x)
{
char *str = calloc(x + 1, 1);
if (str != NULL)
{
for (int i = 0; i < x; i++)
{
str[i] = 'a';
}
}
return str;
}
最後一件事,因爲每個函數,調用者必須檢查函數的返回值,以確保不使用可能NULL指針返回:
int main(void)
{
char *str = maxCharac(2);
if (str != NULL)
{
printf("Test: %s\n", str);
}
}
來源
2017-04-10 14:24:27
LPs
[請參閱爲什麼不投的malloc''中的C'返回值()'和家人討論](http://stackoverflow.com/q/605845/ 2173917)。 –
你必須null結束它。在'for'循環後添加這行,並在'malloc'行中加上'+ 1'。 'str [x] = NULL;' – imreal
你的字符串必須是null-termante,所以你需要在字符後加一個額外的字節。 – LPs