【问题标题】:Printing the content of a file打印文件的内容
【发布时间】:2012-06-12 10:11:43
【问题描述】:
openFile(argv[1],"r");
while(characterBuff != EOF)
{
    characterBuff = fgetc(examFile);
    memoryAlloc += 1;
    string = expandRealloc(string, memoryAlloc);
    appendString(string, characterBuff);
    printf("%s\n", string);
}
closeFile();
free(string);

在以下代码中:我从 printf 获得的输出给了我 ackward 值,例如 [somehash]D[somehash]E[somehash]S[somehash]K

我得到的输出词是“DESK”,但是从内存中取出各种随机的东西,我做错了什么?

注意:以下内容已使用 malloc(sizeof(char)) 分配,并在每次将单个 char 添加到字符串时重新分配。

即我应该得到的输出应该是: D 德 德斯 桌子 但我得到的不是我之前给你看的东西。

编辑:

char* expandRealloc(char* ptrS, size_t n)
{
    void *tmp;
    if((tmp = realloc(ptrS, n)) == NULL)
    {
        printf("Error: Memory leak possible; Closing Program");
        exit(EXIT_FAILURE);
    }
    else
    {
        ptrS = tmp;
        return ptrS;
    }
}

我为 realloc 编写了一个包装函数。感谢您的帮助,但它仍然没有解决问题,我在尝试打印结果时仍然得到 [somecrapmemoryhash][letter][somecrapmemoryhash][letter]。

附加字符串:

void appendString(char* inputString, int inputChar)
{
    int stringLenght = strlen(inputString);
    inputString[stringLenght - 1] = inputChar;
    inputString[stringLenght] = '\0';
}

【问题讨论】:

  • 我猜这是C/C++?
  • 一个大问题开始 - 你对 realloc 的调用被破坏了 - 查看 realloc 的手册页
  • minimal example 是多少?
  • 您可能需要发布appendString的代码

标签: c string realloc


【解决方案1】:

realloc被调用时,它可能会移动分配的内存,所以你需要用realloc返回的值替换你指针的旧内容。

试试

char *temp_string;
    .
    .
    .
temp_string = realloc(string, memoryAlloc);
if(temp_string != NULL)
  string = temp_string;

编辑

让我印象深刻的是,这里的大部分问题是使用用户编写的函数来执行长期以来一直是标准库一部分的事情。在不使用特殊包装器等的情况下修改此代码以使用标准库函数将不再困难,并且会导致更高的可靠性。例如,appendString 函数似乎是这里遇到的许多困难的根源。如果改为使用 strcat 函数(对源代码进行少量修改),则可以避免大量的恶化和拉扯头发。

标准库的存在是有充分理由的。它是一致的、可靠的、经过调试的、有用的,而且——嗯——它是标准。如果这里有人认为他们自己比为标准库做出贡献的数百人更聪明,那么他们很可能是错误的。如果这里有人认为他们不能使用标准库中的函数来执行基本操作,因为他们的需求非常特殊,那么他们很可能是错误的。 C 语言本身并不是特别特别——让我们面对现实吧,花括号没什么大不了的 :-)——C 的力量直接来自“把所有东西都放在一个函数中”的哲学——即来自使用完成任务的函数库。标准库是初级 C 程序员需要学习的最基本的东西,它的使用应该是任何有经验的 C 程序员的第二天性。

分享和享受。

【讨论】:

  • 这会导致内存泄漏,但如果 realloc 失败(即返回 NULL) - 您应该首先将 realloc 的结果分配给临时指针。
  • 为 realloc 写了一个包装函数,并对其进行了修改,但它仍然没有解决打印问题,这对我来说是个问题。代码内容参考第一篇。
  • @PiotrJerzyMamenas - 您能否将appendString 程序的代码添加到原始帖子中?
【解决方案2】:

您的appendString 函数错误 - 更改:

void appendString(char* inputString, int inputChar)
{
    int stringLenght = strlen(inputString);
    inputString[stringLenght - 1] = inputChar;
    inputString[stringLenght] = '\0';
}

到:

void appendString(char* inputString, int inputChar)
{
    int stringLength = strlen(inputString);
    inputString[stringLength] = inputChar;
    inputString[stringLength + 1] = '\0';
}

【讨论】:

  • 我仍然在字符串的开头得到 [weirdmemoryhashes]
  • 你是如何初始化string的?您可能还需要发布这部分的代码。
【解决方案3】:

您的字符串打印问题看起来很可疑,就像您的字符串末尾缺少 NULL 终止符...appendString 是否负责添加终止符?

【讨论】:

  • 是的,它添加了一个终止符。请注意,我的问题不是打印:DESKfo0932jfjewf98wjef98wejf 等,而是 D[Psunflowersign]E[Psunflowersign] 等
猜你喜欢
  • 1970-01-01
  • 2021-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-03
  • 2016-11-11
  • 2015-04-11
相关资源
最近更新 更多