c - 为什么这个 C 程序会变成梨形?我打破了我的缓冲区吗?

标签 c buffer-overflow

我一直在尝试使用 C 语言。我通常使用 PHP 和 javascript。

我输入了“Hello World”,然后输入了这个,这是我从某处网站复制的......

#include <stdio.h>
#include <stdlib.h>
#define MAX 20
int intcmp(const void*v1, const void *v2){
    return (*(int *)v1 - *(int *)v2);
}
main(){
    int arr[MAX], count, key , *ptr;
    printf("Enter %d integer values; press enter after each\n", MAX);
    for (count = 0; count < MAX; count++)
        scanf("%d", &arr[count]);
    puts("Press a key to sort the values");
    getc(stdin);

    qsort(arr, MAX, sizeof(arr[0]), intcmp);

    for(count=0; count < MAX; count++)
        printf("\narr[%d] = %d.", count, arr[count]);

    puts("\nPress a key to continue");
    getc(stdin);

    printf("Enter a val to search for");
    scanf("%d", &key);

    ptr = (int * )bsearch(&key, arr, MAX, sizeof(arr[0]), intcmp);

    if(ptr != NULL){
        int fred =  (ptr - arr);
        printf("%d found at arr[%d]", key ,fred);
    }else{
        printf("%d not found", key);
    }
}

到目前为止一切顺利。我试图了解所有星星的作用,但它正在落到位(哈哈 - meteor :)

但是,如果我输入一个 float ,例如21.45 当它要求我输入 20 个整数时,它会冲到“输入要搜索的值”,并用奇怪的数字填充了 20 个数组值。

我是否造成了某种缓冲区溢出?我意识到应该检查输入 - 但我很想知道我做了什么。我可以使用我的程序运行任意代码吗? (好吧,不,据我所知……但有人可以吗?)

最佳答案

However, if I type in a float e.g. 21.45 when it asks me for 20 integers, it rushes through to "Enter a val to search for" having filled the 20 array values with weird numbers

如果您输入诸如 21.45 之类的值,则对 scanf("%d") 的调用将失败,因为它不是 int,并将 .45 留在 stdin 中(21 将被提取为有效的 int)到重新处理。这会导致循环一次又一次地重新读取该值(因为它每次都失败)。奇怪的数字是由于数组的元素未初始化。

检查 scanf() 的返回值,它返回分配的次数,如果失败则跳过 stdin 中的任何内容:

int count = 0;
while (count < MAX)
{
    if (1 == scanf("%d", &arr[count]))
    {
        count++; /* OK, so get next. */
    }
    else
    {
        /* !OK, skip invalid input. */
        int c;
        while ((c = fgetc(stdin)) != EOF && c != '\n');
    }
}

关于c - 为什么这个 C 程序会变成梨形?我打破了我的缓冲区吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12688845/

相关文章:

c - C 的结构化模块接口(interface)

c++ - 当引用位于标题中并且应该存在时 undefined reference

c - 为什么这是返回指针的偏移量? "smashing the stack"

c++ - 绕过堆栈保护-缓冲区溢出

c - 使用 fgets() 和推荐的解决方案可能存在安全漏洞?

c - 返回 libc 攻击

c - 这段代码到底做了什么

c - libusb-1.0 热插拔事件在 fork() 之后停止在父级中工作,当子级调用 libusb_exit() 时

c++ - 在C中如何在命令行中定义所有未知宏(在源文件/头文件中使用)

c - 如果有人提示 gets(),为什么不对 scanf ("%s"做同样的事情,...)?