c - strcpy 与 char 指针和 char 数组 C 溢出

标签 c arrays pointers overflow

这就是问题所在: 我有两个字符串 s1 和 s2。我想编写一个函数,获取两个字符串之一并覆盖另一个字符串。

我可以用这段代码(C)来做到这一点:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void modifica_overflow(char *s){
    printf("\n\nAdress where I want write -> %p", (s + strlen(s) + 1));
    strcpy((s + strlen(s) + 1 ), s);
    return;
}

int main(void) {
    char s1[] = "Name";
    char s2[] = "emaN";

    printf("\ns1 Adress -> %p", (void*)s1);
    printf("\ns2 Adress -> %p ", (void*)s2);

    printf("\n\nBefore s1 : %s s2 : %s", s1, s2);
    modifica_overflow(s2);
    printf("\n\nAfter s1 : %s s2 : %s", s1, s2);

    return EXIT_SUCCESS;
}

这是输出:

s1 Adress -> 0061FF2B
s2 Adress -> 0061FF26 

Before s1 : Name s2 : emaN

Adress where I want write -> 0061FF2B

After s1 : emaN s2 : emaN

完美的作品!

但是使用这段代码我崩溃了

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void modifica_overflow(char *s){
    printf("\n\nAdress where I want write -> %p", (s + strlen(s) + 1));
    strcpy((s + strlen(s) + 1 ), s);
    return;
}

int main(void) {
    char *s1 = "Name";
    char *s2 = "emaN";

    printf("\ns1 Adress -> %p", (void*)s1);
    printf("\ns2 Adress -> %p", (void*)s2);

    printf("\n\nBefore s1 : %s s2 : %s", s1, s2);
    modifica_overflow(s1);
    printf("\n\nAfter s1 : %s s2 : %s", s1, s2);



    return EXIT_SUCCESS;
}

如果我评论这一行 strcpy((s + strlen(s) + 1 ), s); 这是输出:

s1 Adress -> 00405086
s2 Adress -> 0040508B

Before s1 : Name s2 : emaN

Adress where I want write -> 0040508B

After s1 : Name s2 : emaN

为什么第二个程序不起作用?

最佳答案

你明白指针和数组的区别吗?

第一种情况: 当您在数组边界之外写入时,UB 就在那里。但数组位于 RW 内存中,您很幸运没有收到 SEGFAULT。

第二种情况 - 指向 RO 内存中字符串文字的指针。你不能在那里写,你会得到即时错误

两者都错了@!@!!你首先需要一本好的 C 书

关于c - strcpy 与 char 指针和 char 数组 C 溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46960279/

相关文章:

c++ - C++ 多行执行同一命令

c - 重用 LodePNG 分配的内存

arrays - Angular2 将嵌套的 json 数组映射到模型

java - java中将ArrayList转换为数组的方法

当定义包含参数时调用不带参数的函数

c++ - 无限的 typedef 函数指针继承可能吗?

c - 函数指针转换

c - 是否有用于获取函数参数列表的 C 预处理器宏?

c++ - 当结构定义在头文件中时,如何在 main() 中创建结构数组?

c++ - 我的代码是什么原因?未处理的异常