在c [duplicate]中的memcpy之后的字符串末尾的垃圾字符appendind


喜欢一个人丶
2025-03-14 05:41:43 (25天前)


我正在学习C.
在下面的代码中,当我尝试做memcpy时,它最后添加了垃圾字符。
没有得到我想念的东西。
请帮忙。

int threshold = passlen - type;
printf(“THRESHOLD:%d \ n”,…

2 条回复
  1. 0# Autistic | 2019-08-31 10-32



    因为你没有

    空值

    在内存中字符串末尾的章程。分配内存时,必须考虑这种情况。然后,有两种方法可以解决您的问题:



    1)




    1. createpass = xcalloc(len+1, sizeof(char));
      memset(createpass, 0, len+1);

    2. </code>


    要么



    2)




    1. createpass = xcalloc(len+1, sizeof(char));
      memset(createpass, 0, len+1); // option, because the ‘sprintf’ will fill a ‘\0’ at the end of string automatically.
      sprintf(createpass, “%s%s”, userpass, salt);

    2. </code>


    INJOY。


登录 后才能参与评论