我使用自定义函数连接几个字符串。函数正常工作,我得到了正确的值,但在几个语句后,char指针中的值被破坏。我不明白这背后的原因。以下是更大功能的一部分。我只是提供代码直到腐败发生的地方
char* my_strcpy(char*dest, const char* src, int hasLen, int length) {
if (!hasLen) {
while ((*dest = *src++))
++dest;
} else {
while (length-- && (*dest = *src++))
++dest;
}
return dest;
}
int addSubscriptionInCache(subs_t* subs, str* pres_uri, int read_response) {
redisReply *reply;
char temp_key[1] = "";
char *tk = my_strcpy(temp_key, "", 0, 0);
char *subs_cache_key = tk;
char temp_value[1] = "";
char *tv = my_strcpy(temp_value, "", 0, 0);
char *subs_cache_value = tv;
tk = my_strcpy(tk, SUBSCRIPTION_SET_PREFIX, 0, 0);
tk = my_strcpy(tk, "-", 0, 0);
tk = my_strcpy(tk, subs->pres_uri.s, 0, 0);
tk = my_strcpy(tk, ":", 0, 0);
tk = my_strcpy(tk, subs->event->name.s, 0, 0);
*tk = '\0';
// this prints correctly.
printf("subs_cache_key: %d %s \n", strlen(subs_cache_key), subs_cache_key);
int subs_cache_value_len = subs->callid.len + subs->to_tag.len + 1; // add 1 for :
tv = my_strcpy(tv, subs->to_tag.s, 1,subs->to_tag.len);
tv = my_strcpy(tv, ":", 0, 0);
tv = my_strcpy(tv, subs->callid.s, 1,subs->callid.len);
*tv= '\0';
// this prints correctly.
printf("subs_cache_value: %d %s \n", strlen(subs_cache_value), subs_cache_value);
//add in pipeline
redisAppendCommand(redis_context, "SADD %s %s", subs_cache_key, subs_cache_value))
//set expires
redisAppendCommand(redis_context, "EXPIRE %s %d", subs_cache_key, subs->expires);
// create hash for to_tag:call_id
int argc = 0;
char *arvg[22];
size_t argvlen[22];
// this prints fine.
printf("Before corruption: %s", subs_cache_value);
arvg[argc] = "HMSET";
// below prints corrupted values
printf("After corruption: %s", subs_cache_value);
printf("After corruption: %s", subs_cache_key);
argvlen[argc] = 5;
argc++;
arvg[argc] = subs_cache_value;
argvlen[argc] = subs_cache_value_len;
argc++;
.......
//rest of the code
}
我正在使用自定义函数,以便不会反复遍历整个字符串。
请帮助我理解我是否因为发生腐败而做了一些事情。
由于
答案 0 :(得分:1)
你有
char temp_key[1] = "";
char *tk = my_strcpy(temp_key, "", 0, 0);
然后在tk
的后续调用中继续使用my_strcpy
。
问题在于你没有足够的记忆力。使用超出有效限制的内存会导致未定义的行为。
使用类似:
char temp_key[1000] = ""; // Make the size large enough for
// the kinds of strings you are
// expecting to see.
同样,使用:
char temp_value[1000] = "";