strncpy or strlcpy in my case

前端 未结 6 1284
执笔经年
执笔经年 2020-12-10 11:21

what should I use when I want to copy src_str to dst_arr and why?

char dst_arr[10];
char *src_str = \"hello\";

P

6条回答
  •  伪装坚强ぢ
    2020-12-10 11:37

    First of all, your dst_ptr has no space allocated and you haven't set it to point at the others, so assigning anything to that would probably cause a segmentation fault.

    Strncpy should work perfectly fine - just do:

    strncpy(dst_arr, src_str, sizeof(dst_arr));
    

    and you know you wont overflow dst_arr. If you use a bigger src_str you might have to put your own null-terminator at the end of dst_arr, but in this case your source is < your dest, so it will be padded with nulls anyway.

    This works everywhere and its safe, so I wouldn't look at anything else unless its intellectual curiousity.

    Also note that it would be good to use a non-magic number for the 10 so you know the size of that matches the size of the strncpy :)

提交回复
热议问题