【发布时间】: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