Git 项目的源码禁止开发者使用 C 标准库中的某些函数,原因是这些函数太容易被误用,就算使用得当也很容易出问题。因此 Git 的源码增加了一个 banned.h 的头函数,一旦你使用了这些被禁用的函数,将在编译时报错。
这些函数包括:
#ifndef BANNED_H
#define BANNED_H
/*
* This header lists functions that have been banned from our code base,
* because they're too easy to misuse (and even if used correctly,
* complicate audits). Including this header turns them into compile-time
* errors.
*/
#define BANNED(func) sorry_##func##_is_a_banned_function
#undef strcpy
#define strcpy(x,y) BANNED(strcpy)
#undef strcat
#define strcat(x,y) BANNED(strcat)
#undef strncpy
#define strncpy(x,y,n) BANNED(strncpy)
#undef strncat
#define strncat(x,y,n) BANNED(strncat)
#undef sprintf
#undef vsprintf
#ifdef HAVE_VARIADIC_MACROS
#define sprintf(...) BANNED(sprintf)
#define vsprintf(...) BANNED(vsprintf)
#else
#define sprintf(buf,fmt,arg) BANNED(sprintf)
#define vsprintf(buf,fmt,arg) BANNED(sprintf)
#endif
#endif /* BANNED_H */
banned.h 源码 https://gitee.com/mirrors/git/blob/master/banned.h
我听够了你不明白C的哲学,C的简洁,C的理念,这些话。
我听够了有的人一边说着可以有节制的使用,一边别人稍微加一点限制就大肆批判一通。
咱就不能老老实实说句真话吗?C的设计没有那么好,它的设计里有一堆坑,这些坑一般都已被熟知(但是其实也没有那么多人清楚)。还记得大明湖畔的gets吗?
strncpy有两个问题,第一,它可能会导致字符串末尾没有NUL(之后哪怕一个简单的strlen也会越界);第二,它会有性能问题,因为它会(不必要地)把缓冲区的末尾填满NUL,比如缓冲区是4096字节,哪怕源字符串为空,它也会把4096填满NUL。