我写了这个函数来从文件中读取一行:
const char *readLine(FILE *file) {
if (file == NULL) {
printf("Error: file pointer is null.");
exit(1);
}
int maximumLineLength = 128;
char *lineBuffer = (char *)malloc(sizeof(char) * maximumLineLength);
if (lineBuffer == NULL) {
printf("Error allocating memory for line buffer.");
exit(1);
}
char ch = getc(file);
int count = 0;
while ((ch != '\n') && (ch != EOF)) {
if (count == maximumLineLength) {
maximumLineLength += 128;
lineBuffer = realloc(lineBuffer, maximumLineLength);
if (lineBuffer == NULL) {
printf("Error reallocating space for …Run Code Online (Sandbox Code Playgroud) 例如:
char * myString = malloc(sizeof(char)*STRING_BUFFER_SIZE);
free(myString);
free(myString);
Run Code Online (Sandbox Code Playgroud)
这样做会有不良副作用吗?
许多C代码释放指针调用:
if (p)
free(p);
Run Code Online (Sandbox Code Playgroud)
但为什么?我认为C标准说在free给定NULL指针的情况下函数不会做任何事情.那为什么要另外明确检查?