简体   繁体   中英

What happens when you give a null string to a C standard function?

There are many endearing string functions in the C standard library, such as (in string.h )

char *strcat(char *str1, const char *str2);

or (in stdlib.h )

long int strtol(const char *nptr, char **endptr, int base);

(Ignore the wisdom of calling these functions, for the purposes of this question.)

What will happen if I pass any of these functions a NULL pointer? (I mean (char *) 0 , not the empty string.)

I haven't found any answers in the man pages or on the web.

This leads me to think it's implementation-defined, but it could just as well mean an automatic segmentation fault; no special error behavior or return values are specified, either.

Could the behavior even vary from function to function, within the same implementation?

The C standard says it in 7.21.1 String Function Conventions, clause 2 :

Unless explicitly stated otherwise in the description of a particular function in this subclause, pointer arguments on such a call shall still have valid values, as described in 7.1.4.

7.1.4 Use of library functions :

If an argument to a function has an invalid value (such as a value outside the domain of the function, or a pointer outside the address space of the program, or a null pointer, or a pointer to non-modifiable storage when the corresponding parameter is not const-qualified) or a type (after promotion) not expected by a function with variable number of arguments, the behavior is undefined.

strcat() 's description in 7.21.3.1 says nothing about the NULL pointer being a valid input, hence, I conclude, the behavior is officially undefined if any of its input pointers is NULL.

The standard doesn't say anything, so it's undefined behaviour. On many platforms, you'll get a seg-fault, because it will be dereferencing a null pointer.

除非指定了函数对NULL值的作用(例如endptr是NULL定义),否则结果为undefined - 崩溃,错误代码,中止或恶魔。

The C specification doesn't mention what will happen if you pass erroneous arguments to eg strcat and similar functions, so it's entirely implementation dependent. But I would bet not many implementations check for NULL parameters in release builds at least.

It will be implementation depended. But you will be getting segfaults on many implementations. coz since the string function is extensively used, these library function usually dosent do the nullcheck. (must be because for efficiency)

EDIT : As @Alex mentioned it's not implementation dependent; it's undefined.

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