c - 缓冲区溢出 - 覆盖字符串

标签 c buffer-overflow

我遇到了一个我发现的问题。鉴于以下情况:

int match(char *s1, char *s2) {
    while( *s1 != '\0' && *s2 != '\0' && *s1 == *s2 ){
        s1++; s2++;
    }
    return( *s1 - *s2 );
}

int main() {
    char str1[8], str2[8];
    scanf("%s", str1);
    scanf("%s", str2);
    if (match(str1, str2) == 0)
        printf("They are the same.\n");
    else
        printf("They are not the same.\n");
}

可以使用哪两个不同值的输入字符串来使程序打印消息“它们相同”? (以上代码不可更改)

我理解当数组被添加到堆栈时,它们被“推”入其中并且信息被写入相同的方向。因此,如果我向 str2 输入“AAAAAAAAA”(A x 9),它将溢出并且 str1 将打印“A”。

我的第一次尝试是为 str2 输入 A x 16,希望程序会用 8 个 A 覆盖 str1 中的值,而程序只会读取 str2 中的 8 个值。 str1 确实具有 A x 8 的值,但 str2 保留其 A x 16 的值。

有没有办法用它来解决这个问题?还是我的想法不对?

编辑:这个问题本来是要在安装了过时的、因此易受攻击的 Linux 版本的特定机器上运行的。我已经通过 gdb 运行程序,它显示这两个字符串在内存中彼此相邻并且 str2 溢出到 str1。那么我的问题是,我可以使用它使 str2 和 str1 在比较它们时看起来与程序相同吗?

最佳答案

What two input strings of different values can be used to cause the program to print the message "They are the same"? (The code above can not be altered)

不存在这样定义明确的场景。这些要求毫无意义。

I understand that when the arrays are added to the stack, they are "pushed" into it and information is written in the same direction. So if I were to enter "AAAAAAAAA" (A x 9) to str2, it would overflow and str1 would print "A".

这是不正确的。缓冲区 str1(可以包含 7 字母 + 1 个空终止符)会溢出,从那里任何事情都可能发生,您会调用未定义的行为。可能的未定义行为的一些示例是:段错误/崩溃和烧毁,或者程序似乎可以正常工作。

不保证 str2 与 str1 相邻分配。也不能保证 str1 在 str2 之前分配。甚至没有任何保证将它们分配到堆栈上,尽管这很有可能。

Is there a way to use this to solve this problem?

没有。

Or am I thinking about this the wrong way?

是的。

关于c - 缓冲区溢出 - 覆盖字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19361714/

相关文章:

c - Pthreads 在执行时更新全局 2D 数组段错误

c - 需要帮助了解缓冲区溢出及其利用

c - 为什么我在这段代码中出现缓冲区溢出?

Bash 读取行缓冲区溢出

c - 内存地址

c - 一台服务器绑定(bind)不同的端口

c - gstreamer gst_element_seek 在 mpeg2ts 上非常慢

无法使用 OpenAL 捕获 send() 失败

C 如何使用 esc 退出 while 循环