c - 使用 strchr 时如何解决 'munmap_chunk(): invalid pointer Aborted'
问题描述
我正在使用 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
via的值tmp++;
。因此,当您tmp
在函数结束时释放时,它不再指向最初分配的内存。
每个内存分配都必须与free
具有相同地址的调用相匹配。
推荐阅读
- android - RecyclerView 不显示数据库片段中的数据
- typescript - 使用类型作为函数
- python - Flask-limiter - 在 redis 中添加自定义键名
- soap - 如何通过 SOAP 调用 NetSuite SuiteScript - Ballerina Lang
- javascript - 如何使用引导程序从 datepicker 获取日期并在另一个 div 中显示日期
- flutter - 颤振:未定义的名称“上下文”
- liquibase - Liquibase:如何使用
变更集具有 runAlways true? - drop-down-menu - 有没有办法在下拉菜单中修改字体?
- opengl - OpenGL:单个三角形平面的正面和背面是否有不同的光效?
- google-cloud-functions - 从 CLI 触发 Firebase 模拟器中的 PubSub 事件