简体   繁体   中英

What would happen if after using malloc it returned a NULL pointer and you went ahead and try to use that pointer?

我知道在使用malloc之后,你必须确保返回的指针不是NULL,但如果你没有,那该怎么办?

Regarding using a null pointer with the * operator, the 2011 C standard (committee draft N1570) says in clause 6.5.3.2, paragraph 4: “If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.” A footnote notes that a null pointer is an invalid value.

Many people will think of using a null pointer as trying to access memory with an invalid address, which causes an exception and terminates your program on common hardware and operating systems. However, modern compilers and their optimizers are very complicated and perform a variety of abstract mathematical transformations on your code. The result is that, if your code has undefined behavior, a variety of surprising things can happen.

Using a null pointer in other ways can also cause undefined behavior, including using it with the -> operator, the subscript operator, the + and - binary operators, and the relational operators ( < , <= , > , and >= ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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