字符串变量的安全处理 [英] Secure handling of string variables
问题描述
您好,我是 C 的新手,简而言之,作为课堂作业的一部分,我正在执行以下操作:
Hello I'm quite new to C and in a nutshell I was doing the following as part of my assignment in class:
foo (char *var) {
printf(var);
}
有人告诉我这是不好的做法并且不安全,但我的导师没有得到更多详细信息.我假设如果 var 的字符串值可由用户控制,它可以用于执行缓冲区溢出吗?我将如何正确强化此代码?我是否必须限制 str 长度或其他什么?
I was told that this is bad practice and insecure but did not get much detailed information on this by my tutor. I assume that if the string value of var is controllable by the user it may be used to perform a bufferoverflow? How would I properly harden this code? Do I have to limit the str length or something?
干杯&谢谢!
推荐答案
你应该使用:
printf("%s", var);
相反.按照你的方式,我可以输入 %s
作为我的输入,并且 printf
会在它寻找要打印的字符串时读取一段随机内存.这可能会导致任何数量的意外行为.
instead. The way you have it, I could enter %s
as my input, and printf
would read a random piece of memory as it looked for a string to print. That can cause any amount of unexpected behaviour.
这篇关于字符串变量的安全处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!