I followed How to memset char array with null terminating character? to add a null terminator when using the C memset
api.
The code worked; I no longer got odd in-memory chars added to the end of my malloc'd char array, due to the null terminator.
/* memset does not add a null terminator */
static void yd_vanilla_stars(size_t *number_of_chars, char *chars_to_pad)
{
memset(chars_to_pad, 0, *number_of_chars+1);
memset(chars_to_pad,'*',*number_of_chars);
}
Is there a more elegant way of achieving the same?
The question suggests that chars_to_pad
points to memory allocated using malloc()
. Another alternative is to use calloc()
instead. This function automatically zero-initializes the allocated memory, so there is no need to zero the allocation in a separate step.
An example might look like this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
size_t arr_sz = 11;
char *arr = calloc(arr_sz, sizeof *arr);
memset(arr, '*', arr_sz - 1);
puts(arr);
return 0;
}
Program output:
**********