相关疑难解决方法(0)

C逐行读取文件

我写了这个函数来从文件中读取一行:

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)

c file-io std line

165
推荐指数
7
解决办法
73万
查看次数

当你尝试释放()已经释放c中的内存时会发生什么?

例如:

char * myString = malloc(sizeof(char)*STRING_BUFFER_SIZE);
free(myString);
free(myString);
Run Code Online (Sandbox Code Playgroud)

这样做会有不良副作用吗?

c memory memory-management

29
推荐指数
7
解决办法
1万
查看次数

在调用free之前检查NULL

许多C代码释放指针调用:

if (p)
  free(p);
Run Code Online (Sandbox Code Playgroud)

但为什么?我认为C标准说在free给定NULL指针的情况下函数不会做任何事情.那为什么要另外明确检查?

c

22
推荐指数
3
解决办法
1万
查看次数

标签 统计

c ×3

file-io ×1

line ×1

memory ×1

memory-management ×1

std ×1