Reputation: 1645
I am concatenating few strings using a custom function. The functions works correctly and I get the proper values but after few statements the values in the char pointers gets corrupted. I do not understand the reason behind this. Below is the part of a larger function. I am just providing the code till where the corruption happens
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
}
I am using the custom function so that not to traverse the whole string again and again.
Please help me understand if I have done something because of which corruption is happening.
Thanks
Upvotes: 0
Views: 844
Reputation: 206707
You have
char temp_key[1] = "";
char *tk = my_strcpy(temp_key, "", 0, 0);
and go on to use tk
in subsequent calls to my_strcpy
.
The problem is that you don't have enough memory. Using memory beyond the valid limits leads to undefined behavior.
Use something like:
char temp_key[1000] = ""; // Make the size large enough for
// the kinds of strings you are
// expecting to see.
Similarly, use:
char temp_value[1000] = "";
Upvotes: 1