c - 如何重写以下函数,使其不再容易受到堆栈缓冲区溢出的影响?

标签 c stack-overflow

我需要重写该函数,使其不再容易受到堆栈缓冲区溢出的影响。

void hello (char *tag)
{
   char inp [16];

   printf("enter value for %s:", tag);
   gets(inp);
   printf("hello your %s is %s\n", tag, inp);
}

此外, 如何重写以下其他代码以避免缓冲区溢出:

int main (int argc, char *argv[ ]) {
    int valid=FALSE;
    char str1[8];
    char str2[8];

    next_tag(str1);
    gets(str2);
    if (strncmp(str1,str2,8)==0)
        valid=TRUE;
    printf("buffer: str1(%s),str2(%s),valid(%d) \n", str1, str2, valid);
}

最佳答案

只需使用 fgets()而不是 gets()。它允许您限制存储在缓冲区中的字符数。

关于c - 如何重写以下函数,使其不再容易受到堆栈缓冲区溢出的影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4471306/

相关文章:

arrays - 找到两个排序数组的中位数 - 我得到 stackoverflow 异常

c++ - 将函数的返回值存储到指向 char 变量的指针中是正确的做法吗?

c++ - 如何在两个 Lua 脚本之间共享数据

mysql - 局部变量语法错误

java - StackOverflowError 在 Java 中是什么意思?它的解决方法是什么?

asp.net - VimService55.XmlSerializers.dll 中发生类型 'System.StackOverflowException' 的未处理异常

java - eclipse中的堆和栈

c - Windows 中的 UTF-8

c - emacs gdb 跳转到光标

c - 使用带有双指针的 malloc 时出现段错误