如何摆脱动态分配的 char* 的垃圾值

How to get rid of Garbage value of char* dynamically allocated

我正在尝试弄清楚如何在动态分配的 char* str 中没有垃圾值。

 char* str = (char*)malloc(10*sizeof(char));

因为我想使用这个 char* 来连接字符串,所以我想知道如何不具有如下所示的垃圾值,

printf("str looks like this %s\n",str);

那么输出是

譁�蟄怜

此外,当我使用 Ubuntu 时会发生这种情况,但使用 mac 时不会发生。 我如何确保它没有垃圾值,以便我以后可以很好地连接?

... how to not to have garbage value ...
How do I make sure that it does not have garbage values so that I can concatenate nicely later?

使用calloc()零填充分配的内存。

char* str = calloc(10, sizeof *str);
if (str) {
  printf("str looks like this <%s>\n",str);
}

最昂贵的方法是使用 calloc 函数。

char* str = calloc(10, sizeof(*str));

最快的方法:

char* str = malloc(10 * sizeof(*str));
*str = 0;