微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用strchr时如何解决'munmap_chunk:无效的指针异常终止'

如何解决使用strchr时如何解决'munmap_chunk:无效的指针异常终止'

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

#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更改tmp++;的值。因此,在函数末尾释放tmp时,它不再指向最初分配的内存。

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。