C反向功能不适用于32个字符

Chr*_*nam 0 c string while-loop

为了测试我的技能,我正在尝试编写自己的几个标准库函数版本.我写了一个替代strlen(),strlength():

int strlength(const char *c){
    int len = 0;
    while (*c != '\0') {
        c++;
        len++;
    }
    return len;
}
Run Code Online (Sandbox Code Playgroud)

其中不包括null-terminator,我正在尝试编写一个函数来反转字符串.这个:

char *reverse(const char *s){
    char *str = (char *)malloc(sizeof(char) * strlength(s));
    int i = 0;
    while (i < strlength(s)) {
        str[i] = s[(strlength(s) - 1) - i];
        i++;
    }
    str[strlength(s)] = '\0';
    return str;
}
Run Code Online (Sandbox Code Playgroud)

适用于每个字符串,除了一个包含32个字符(不包括null-terminator)之类的字符串foofoofoofoofoofoofoofoofoofoofo.它挂在reverse()函数while循环中.对于所有其他数量的字符,它的工作原理.为什么会这样?

Dao*_*Wen 6

你的缓冲区str是1.你的写入溢出到堆的其余部分.

As for why it works for values other than 32, my guess is that it has to do with the heap's memory alignment. The compiler is adding extra padding for smaller buffer sizes, but 32 bytes is nicely aligned (it's a power of 2, multiple of 8, etc.), so it doesn't add the extra padding and that's causing your bug to manifest. Try some other multiples of 8 and you'll probably get the same behavior.

  • s /你的堆栈的其余部分/堆的一部分/(很可能;因为str是malloced (2认同)