简体   繁体   English

C atoi函数的错误可能性

[英]potential for error in C atoi function

Is there anything you could supply to the atoi function that would produce an error (that may or may not crash the program)? 是否有任何可以提供给atoi函数会产生错误的东西(可能会或可能不会使程序崩溃)?

EDIT: An error is defined as anything that would produce a compilation error, or something that would cause the program to terminate during execution. 编辑:错误定义为会产生编译错误的任何内容,或者导致程序在执行期间终止的内容。

anything that would produce a compilation error 任何会产生编译错误的东西

If the argument you supply to atoi() is of an incompatible type, you'll get a compile-time error. 如果您提供给atoi()的参数是不兼容的类型,则会出现编译时错误。

something that would cause the program to terminate during execution 导致程序在执行期间终止的东西

If you supply atoi() with an invalid const char* pointer, the behaviour of your code will be undefined. 如果为atoi()提供了无效的const char*指针,则代码的行为将是未定义的。 While nothing is guaranteed, if the pointer is NULL or points to unreadable memory the program will likely terminate (this depends on the OS and the hardware architecture). 虽然没有任何保证,但如果指针为NULL或指向不可读的内存,程序可能会终止(这取决于操作系统和硬件架构)。

I suspect the question is more along the lines of 'do I have to sanitize the input from a source I dont trust before passing it to atoi?' 我怀疑这个问题更像是“在将它传递给atoi之前,我是否必须对来自我不相信的来源的输入进行消毒?”

The behavior of a correctly written atoi function is specified for most cases. 在大多数情况下,指定了正确编写的atoi函数的行为。 It will convert characters to numbers until it hits something non numeric and then stop. 它会将字符转换为数字,直到它遇到非数字的东西,然后停止。 However atoi is considered vulnerable to overflows 然而,atoi被认为容易溢出

You should use strtol instead; 你应该使用strtol; its spec is tighter 它的规格更紧凑

Of course the implementation in your c runtime could be broken - but then there is not a lot you can do about that 当然,你的c运行时的实现可能会被打破 - 但是你可以做很多事情

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM