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