You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多次调用realloc导致程序崩溃,替换为大内存malloc则正常且Valgrind报mmap错误的问题求助

多次调用realloc导致程序崩溃,替换为大内存malloc则正常且Valgrind报mmap错误的问题求助

各位大佬好,我最近写C代码的时候碰到个头疼的问题,想请教下大家:

当输入的字符串长度超过16个字符时,用realloc逐步扩容的程序就直接崩溃了,但如果我把realloc的逻辑去掉,换成直接调用malloc(sizeof(char) * 1000)分配一块足够大的内存,程序就能完美运行。

我用Valgrind调试时,它给出了这样的错误信息:

valgrind: mmap(0x17a000, 708608) failed in UME with error 22 (Invalid argument). valgrind: this can be caused by executables with very large text, data or bss segments.

可我有点搞不懂,不管是realloc还是malloc,字符串都是分配在堆上的啊,为什么会出现这种差异呢?

下面是我写的部分代码(realloc的逻辑还没写完,但核心是每次循环尝试扩容):

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

char *getstr()
{
    char *buf = malloc(sizeof(char));

    if (buf == 0)
        return 0;

    size_t i = 0;
    int tmp;

    while (1)
    {
        if (i == SIZE_MAX)
        {
            errno = ERANGE;
            buf[i] = 0;
            return buf;
        }
        tmp = getchar();
        switch (tmp)
        {
            case EOF:
            case '\n':
                buf[i] = 0;
            case 0:
                return buf;
        }
        buf[i] = tmp;

        if (reallo...

备注:内容来源于stack exchange,提问作者Display name

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 13:39:52