我正在学习C。 在下面的代码中,当我尝试执行memcpy时,它在末尾添加了垃圾字符。 没有得到我所缺少的。 请帮忙。
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
CONNECTIVITY_SERVICE );
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();}
输出:
int threshold = passlen - type;
printf("THRESHOLD: %d\n",threshold);
printf("TYPE: %d\n",type);
printf("decodedpass: %s len(decodepass): %d\n",decodedpass,strlen(decodedpass));
strncpy(salt, &decodedpass[threshold] , type);
printf("-------SALT: %s\n",salt);
salt[type] = '\0';
printf("-------LASTSALT: %s\n",salt);
saltlen = strlen(salt);
printf("-------SALTLEN: %d\n",saltlen);
int len = saltlen + userpasslen;
printf("-------USERPASS: %s\n",userpass);
printf("-------LENSALTandUSERPASSLEN: %d\n",len);
createpass = xcalloc(len, sizeof(char));
memcpy(createpass, userpass, userpasslen);
printf("-------len(createpass):%d userpasslen:%d len(salt):%d saltlen:%d salt:%s\n",strlen(createpass),userpasslen,strlen(salt),saltlen,salt);
printf("-------CREATEPASSmemcpy1: %s\n",createpass);
memcpy(createpass + userpasslen, salt, saltlen);
printf("-------CREATEPASSmemcpy2: %s len(createpass):%d\n",createpass,strlen(createpass));
答案 0 :(得分:1)
因为在内存中字符串的末尾没有 null 宪章。分配内存时,必须考虑这种情况。然后,有两种方法可以解决您的问题:
1)
createpass = xcalloc(len+1, sizeof(char));
memset(createpass, 0, len+1);
或
2)
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);
享受。