How to resolve 'munmap_chunk(): invalid pointer Aborted' when using strchr

599 views Asked by At

I am writing a function in C using strchr. Basically, given a string from parameter, the code will identify any '\n' exists in (char content[]) and copy the string before '\n' to str using strncpy. String after '\n' is copied using strchr. The output of the program looks fine, but the problem is that I am having a message at the end of the program showing: 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;
}
1

There are 1 answers

2
Daniel Walker On BEST ANSWER

You keep changing the value of tmp via tmp++;. Therefore, when you free tmp at the end of the function, it is no longer pointing to the memory which was originally allocated.

Each memory allocation must be matched up with a call to free with the same address.