Home > Software design >  How to get rid of Garbage value of char* dynamically allocated
How to get rid of Garbage value of char* dynamically allocated

Time:11-11

I am trying to figire out how to not have garbage values in dynamically allocated char* str.

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

since I want to use this char* to concatenate strings after, so I want to know how to not to have garbage value like below,

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

then output is

譁�蟄怜

Also, this happens when I am using Ubuntu, but does not happen with mac. How do I make sure that it does not have garbage values so that I can concatenate nicely later?

CodePudding user response:

The most expensive way is to use calloc function.

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

The fastest way:

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

CodePudding user response:

... 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?

Use calloc() to zero fill the allocated memory.

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