malloc()与堆溢出说明

Sta*_*hil 2 c heap buffer-overflow

我有以下代码:

int main(int argc, char *argv[]) {

    int bufferSize = 8;
    //Setting the buffer size here, which can cause a heap overflow
    char *argsStr = malloc(bufferSize);
    char *anotherStr = malloc(bufferSize);

    //If argv[1] is greater than the buffer size, we will have an overflow
    strcpy(argsStr, argv[1]);

    printf("String 1: %s String 2: %s", argsStr, anotherStr);

}
Run Code Online (Sandbox Code Playgroud)

我想导致堆溢出,所以我导入参数'testtesttesttesttesttesttesttesttest'.

我希望,因为argsStr只有大小为8,它将是'testtest',其余的将溢出到anotherStr(8个字节),但我看到: 在此输入图像描述

所以argsStr是'testtesttesttesttesttesttesttesttest'而另一个是'testtesttesttesttest'

为什么是这样?我错过了堆溢出的东西或malloc()

Bar*_*mar 7

printf()不知道或关心你为缓冲区分配了多少内存.当它打印一个带%s格式的字符串时,它会一直打印,直到到达终止的零字节.因此,当它打印时argsStr,它会打印整个内容,即使它溢出了已分配的8个字节.这就是缓冲区溢出问题的原因 - C指针不包含有关分配内存量的任何信息,因此如果不正确检查长度,则可以轻松访问分配空间外的内存.

内存anotherStr显然是在内存之后分配了16个字节argsStr.因此,当您打印它时,它从位置开始argsStr[16],并打印该字符串的最后20个字节.

当然,这是所有未定义的行为,因此您不能依赖任何特定结果.