How to add null terminator to char pointer, when using strcpy

c, char, malloc, pointers, strcpy

Solution

You don't need to. Second argument of `strcpy()` needs to be `nul` terminated, and the first needs to fit the number of characters in source + the `nul` terminator.

The problems in your code are:

You are using `sizeof` operator in wrong way and you are overwriting the `src` pointer by allocating memory again to it.

To get the length of a string you need `strlen()` and you don't need to call `malloc()` on every pointer.

You are getting garbage value because you are copying from uninitialized data since `src` points to a newly allocated space, because of

src = malloc(sizeof(char));

you should not do that.

`sizeof(char) == 1` by definition, so you are allocating space for just 1 byte, which if it was to be a valid C string, has to be `'\0'` because there is room for just 1 character.

The correct `printf()` specifier for a string is `"%s"`, you are using `"%c"` which is for a character.

The correct way to do it is

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
    char       *target;
    const char *src;

    src    = "Test"; /* point to a static string literal */
    target = malloc(1 + strlen(src)); /* allocate space for the copy of the string */
    if (target == NULL) /* check that nothing special happened to prevent tragedy  */
        return -1;

    strcpy(target, src);
    printf("%s\n", target);
    /* don't forget to free the malloced pointer */
    free(target);

    return 0;
}

Problem

I have a program that's attempting to use the `strcpy()` function. I know that when one uses a char array such as: `char array[10]` the null terminator can be set by: `array[0] = '\0';` However, how would I go about setting the null terminator(s) when using char pointers? EDIT: The program compiles, but gives garbage as output ``` #include <stdio.h> #include <string.h> #include <stdlib.h> int main(void) { char *target; char *src = "Test"; target = malloc(sizeof(char)); src = malloc(sizeof(char)); strcpy(target,src); printf("%c\n",target); return 0; } ```

Original source