【问题标题】:How to resolve 'munmap_chunk(): invalid pointer Aborted' when using strchr使用 strchr 时如何解决 'munmap_chunk(): invalid pointer Aborted'
【发布时间】:2021-01-15 16:27:00
【问题描述】:

我正在使用 strchr 用 C 语言编写一个函数。基本上,给定参数中的字符串,代码将识别 (char content[]) 中存在的任何 '\n' 并使用 strncpy 将 '\n' 之前的字符串复制到 str。使用 strchr 复制 '\n' 之后的字符串。程序的输出看起来不错,但问题是我在程序末尾有一条消息显示:munmap_chunk(): invalid pointer Aborted

#define STR_LEN 200

char* print( char content[] )
{
    int i;
    char *str = NULL;
    char *tmp  = NULL;

    tmp = malloc(sizeof(char) * STR_LEN);
    strcpy(tmp, content);
    for( i = 0; content[i] != '\0'; i++ )
    {
        str = malloc(sizeof(char) * STR_LEN);

        if( content[i] == '\n' )
        {    
            /* Copy all string in (char content[]) from beginning until latest '\n' */
            strncpy(str, content, (i+1)); 
        

            /* Copy all string in (char content[]) from latest '\n' until the end   * 
             *
             * tmp is NULL when strchr reaches the 
             * end of (char content[]) and no '\n' was found                        
             */
            if( tmp != NULL )
            {
                /* tmp is remaining string after latest '\n' */
                tmp = strchr(tmp, content[i]); 
                printf("%s", tmp);
                /* 
                 *  Increment of tmp (pointer) make us point to next address 
                 *  so that tmp will not point to same address on the next strchr call 
                 */
                tmp++;
            }
        }
        free(str);
        str = NULL;
    }
    free(tmp);
    tmp = NULL;
    return content;
}

【问题讨论】:

  • 为什么要检查tmp 是否为NULL?您永远不会将其设置为等于 NULL
  • 强制转换malloc 的返回值是不好的做法。另外,如果content 的长度大于或等于STR_LEN,会发生什么?
  • 我假设当 strchr 到达内容末尾并且找不到更多的 '\n' 时 tmp 将变为 NULL?
  • STR_LEN 是预处理器宏吗?也就是说,它是由#define 定义的吗?
  • 内容长度永远小于STR_LEN

标签: c free strchr invalid-pointer


【解决方案1】:

您不断通过tmp++; 更改tmp 的值。因此,当你在函数结束时释放tmp时,它不再指向原来分配的内存。

每个内存分配都必须与具有相同地址的free调用相匹配。

【讨论】:

  • 如果我要删除 tmp++,如何保留 strchr 读取现有字符串上的 '\n' 的功能而不从头开始?
  • 您可以在unsigned int 变量中保留索引。你不断增加索引,然后引用tmp+index
猜你喜欢
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 2017-07-16
  • 1970-01-01
  • 2011-02-11
  • 2014-07-04
  • 2020-07-23
相关资源
最近更新 更多