Using strncpy() to copy const char *

isal picture isal · Feb 9, 2013 · Viewed 12.4k times · Source

I'm very new to C, I'm getting stuck using the strncpy function.\

Here's an example of what I'm working with:

int main()
{

const char *s = "how";

struct test {
    char *name;
};

struct test *t1 = malloc(sizeof(struct test));

strncpy(t1->name, s, sizeof(*s));
t1->name[NAMESIZE] = '\0';

printf("%s\n", t1->name);

}

I have a const char *, I need to set the "name" value of test to the const char. I'm having a really tough time figuring this out. Is this even the correct approach?

Thank you very much!

Answer

Some programmer dude picture Some programmer dude · Feb 9, 2013

Well, you allocate the structure, but not the string inside the structure. You need to do that before you copy to it. Even when you do, you will probably overwrite unallocated memory when you attempt to set the string terminator.

And, due to a hight intake ow wine, I just noticed you actually only copy one character, but it's still undefined behavior.