#include <string.h>
void foo (char *bar)
{
char c[12];
strcpy(c, bar); // no bounds checking
}
int main (int argc, char **argv)
{
foo(argv[1]);
return 0;
}
-1
A
回答
-2
2
另一個實際選項:
void foo (char *bar)
{
char c[12];
snprintf(c, sizeof c, "%s", bar);
}
功能strncpy
不保證生成的字符串由NULL character
終止,因此,你可以有一個bad resulting string.
0
檢查是否長度該bar
小於length of c
。
代碼:
#include <string.h>
void foo (char *bar)
{
char c[12];
if (strlen(bar) < sizeof c) {
printf("avoiding buffer overflow");
strcpy(c, bar);
}
}
int main (int argc, char **argv)
{
foo(argv[1]);
return 0;
}
相關問題
- 1. If/Else Statement
- 2. svg if statement
- 3. If Then Statement
- 4. Javascript If or statement
- 5. if statement with datatables
- 6. if statement and mutate
- 7. Javascript - if statement error
- 8. IF statement validate.js
- 9. Long if statement
- 10. If else statement planets
- 11. Else If Statement Swift
- 12. IF statement == not working
- 13. jQuery IF/Else Statement
- 14. MYSQL if statement question
- 15. jquery if statement issue
- 16. NSArray和「If-statement」
- 17. if statement returns true
- 18. Angular If Statement
- 19. Symfony2 {%if statement%}
- 20. python if statement always
- 21. If else statement problems
- 22. if statement ambiguity
- 23. JavaScript if statement scope
- 24. 「If」,「and」excel statement
- 25. IF Statement Always True
- 26. if statement incorrect
- 27. iMacro If Else Statement
- 28. If-else if statement not working properly
- 29. JavaScript If If Statement + Uncaught TypeError
- 30. If or If-Else Statement Error
「如何使這個代碼利用IF..Statement緩衝區溢出的安全」,沒有必要爲一個if語句,只需使用['strncpy'(HTTPS:/ /linux.die.net/man/3/strncpy),而不是:-) – George
提示您可能還需要檢查參數是否的確存在。 – sjsam
注意,僅僅是避免緩衝區溢出並不能保證你的程序實際上會做正確的事。無論您選擇何種策略來防止緩衝區在任何特定情況下溢出,都應該與程序目的和規範保持一致。 –