0

When I call strncpy() with an uninitialized string like this

strncpy(person->name, string, sizeof(person->name));

and then compile with -Wall and -Werror, and I see this error:

src/parser.c:18:35: error: argument to ‘sizeof’ in ‘strncpy’ call is the same expression as the destination; did you mean to provide an explicit length? [-Werror=sizeof-pointer-memaccess]
   strncpy(person->name, string, sizeof(person->name));

I see that some other posts mentioned array decay in C, is it the same thing in this case? What would be the correct way to use strncpy() in this function then?

Edit: first, I malloc'd the struct as well as the string, and then I called strncpy(). Here is what the struct looks like:

typedef struct {
  char *name;
  int age;
  int phone_num;
} person_t;
Mat
  • 202,337
  • 40
  • 393
  • 406
linlucas
  • 23
  • 7
  • 3
    Ask yourself : "What is the value of `sizeof(person->name);`"? It isn't what you think it is. Once you see this, then ask "what function gives me the number of characters in the buffer?". – PaulMcKenzie Apr 09 '20 at 05:25
  • 3
    `sizeof(person->name)` == `sizeof (char *)`, not `sizeof(the number of bytes malloc-ed)` – Sourav Ghosh Apr 09 '20 at 05:26
  • 1
    Neither of the duplicates are relevant, this question has nothing to do with strlen. Clearly the poster thinks that sizeof will give the size of the allocated block. – john Apr 09 '20 at 05:28
  • Would `strncpy(person->name, string, strlen(string) + 1)` work then? – linlucas Apr 09 '20 at 05:34

0 Answers0