我正在使用 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;
}