Examples of C-language and error-prone Functions
Strncmp
Used to compare whether two strings are equal.
Int strncmp (const char * str1, const char * str2, size_t n );
Defense point: the length of n must be sizeof (str1) or strlen (str1) + 1. Make sure that "\ 0" is also compared, otherwise, "AB" and "abc" are also judged to be equal when n = 2.
#include
#include
int main(){ char arg[10]; scanf("%s", arg); if(!strncmp("jack", arg, sizeof("jack"))){ printf("right !\n"); } else { printf("%s is wrong\n", arg); } return 0;}
Strtol
Strtol () converts the nptr parameter string to the Growth integer number based on the base parameter.
Long int strtol (const char * nptr, char ** endptr, int base );
Strtol () skips the space character before the nptr parameter until base conversion starts when a number or positive or negative sign is encountered, and when a non-number or string ends ('\ 0 ') end the conversion and return the result. If the endptr parameter is not NULL, the character pointer in the nptr that is terminated due to an exception is returned by endptr. If the endptr parameter is NULL, no invalid string is returned.
Defense point: Use '\ 0' as follows '! = * Endstr ensures that arg contains all numbers. If arg is NULL, The endstr is also empty after conversion, and an error occurs when a NULL pointer is referenced. Therefore, if you cannot determine whether arg is NULL, You need to perform non-NULL judgment on endstr.
#include
int main(){ char *arg; char *endstr; scanf("%s", arg); int var = strtol(arg, &endstr, 10); if(NULL == endstr){ printf("err!\n"); goto err; } if(var<0 || var>100 || '\0'!=*endstr){ printf("wrong endstr: %s!\n", endstr); } else { printf("%d is OK!\n", var); } err: return 0;}
We recommend that you use calloc instead of malloc.
Void * calloc (size_t n, size_t size );
After the memory is dynamically allocated, calloc automatically initializes the memory space to zero, while malloc does not initialize, and the data in the memory is random junk data.
# Include
Int main () {char * str = (char *) malloc (sizeof (char) * 100); // equivalent to the static character array str [100], however, typedef struct pointer {int data; struct pointer * p;} pt; pt * p = (pt *) calloc (1, sizeof (struct pointer )); // dynamically apply for struct space return 0 ;}