局部变量的突然数据损坏

Sudden data corruption of local variable

我正在使用自定义函数连接几个字符串。这些函数工作正常,我得到了正确的值,但在几条语句之后,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 = '[=10=]';

    // 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= '[=10=]';
    // 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
    }

我正在使用自定义函数,这样就不会一遍又一遍地遍历整个字符串。

请帮助我理解我是否因为腐败而做了某事。

谢谢

你有

char temp_key[1] = "";
char *tk = my_strcpy(temp_key, "", 0, 0);

并在随后对 my_strcpy 的调用中继续使用 tk

问题是您没有足够的内存。使用超出有效限制的内存会导致未定义的行为。

使用类似于:

char temp_key[1000] = "";  // Make the size large enough for
                           // the kinds of strings you are 
                           // expecting to see.

同样,使用:

char temp_value[1000] = "";