C-如何从Stdin或文件内存保存中读取字符串行 [英] C - How to Read String Lines from Stdin or File Memory Save

查看:72
本文介绍了C-如何从Stdin或文件内存保存中读取字符串行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要读取行的版本可以节省内存.我有这个工作"的解决方案.但是我不确定它在内存中的行为.当我启用free(text)时,它可以工作几行,然后出现错误.因此,尽管我分配了文本,但现在文本和结果都不会被释放.那是对的吗 ?那为什么会这样呢?

I need a version of read line that is memory save. I have this "working" solution. But I'm not sure how it behaves with memory. When I enable free(text) it works for a few lines and then I get an error. So now neither text nor result is ever freed although I malloc text. Is that correct ? And why is that so ?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* readFromIn()
{
    char* text = malloc(1024);
    char* result = fgets(text, 1024, stdin);
    if (result[strlen(result) - 1] == 10)
        result[strlen(result) - 1] = 0;
    //free(text);
    return result;
}

我有很多短行需要阅读,我还需要stdin可以用FILE*手柄替换.因为我只有几行,所以不需要重新分配文本.

I have A LOT of short lines to read with this and I also need stdin to be replaceable with a FILE* handle. There is no need for me to realloc text because I have only short lines.

推荐答案

fgets返回指向字符串的指针,因此在fgets行之后,result将与text是相同的内存地址.然后,当您呼叫free (text);时,您将返回无效的内存.

fgets returns a pointer to the string, so after the fgets line, result will be the same memory address as text. Then when you call free (text); you are returning invalid memory.

完成result

您还可以通过结构化代码以传递类似于以下内容的缓冲区来避免使用malloc/free:

You could also avoid the malloc/free stuff by structuring your code to pass a buffer something like this:

void parent_function ()
{
    char *buffer[1024];

    while (readFromIn(buffer)) {
        // Process the contents of buffer
    }
}

char *readFromIn(char *buffer)
{
    char *result = fgets(buffer, 1024, stdin);
    int len;

    // fgets returns NULL on error of end of input,
    // in which case buffer contents will be undefined
    if (result == NULL) {
        return NULL;
    }

    len = strlen (buffer);
    if (len == 0) {
        return NULL;
    }

    if (buffer[len - 1] == '\n') {
        buffer[len - 1] = 0;

    return buffer;
}

如果要处理许多小而短暂的项目,则避免使用malloc/free可能是明智的选择,这样内存就不会碎片化,并且应该也更快.

Trying to avoid the malloc/free is probably wise if you are dealing with many small, short lived items so that the memory doesn't get fragmented and it should faster as well.

这篇关于C-如何从Stdin或文件内存保存中读取字符串行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆