Question

I keep getting this malloc.c assertion failure. I've looked at other similar questions but can't seem to find a solution. This is my code...I've placed a printf at the spot JUST before it errors out.

int ParseCommand(char *cmd_line, struct command_t *cmd, char **paths)
{
    int argc;
    char **line_ptr;
    char *tmp_name = (char *) malloc(sizeof(MAX_PATH_LEN));

    /* Initialization */
    line_ptr = &cmd_line;
    argc = 0;
    cmd->argv[argc] = (char *) malloc(MAX_ARG_LEN);

    /* Fill argv[] Array */
    while((cmd->argv[argc] = strsep(line_ptr, WHITESPACE)) != NULL) {
        cmd->argv[++argc] = (char *) malloc(MAX_ARG_LEN);
    }

    /* Set The Command Name & argc */
    cmd->argc = argc - 1;
    tmp_name = LookupPath(cmd->argv, paths);

    if(tmp_name == NULL) {
        Fatal("Command Not Found!");
    }
    printf("HERE 4\n");
    cmd->name = (char *) malloc(sizeof(tmp_name));
    strncpy(cmd->name, tmp_name, MAX_PATH_LEN);
    free(tmp_name);
}

Error is:

smallsh: malloc.c:2369: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.
Aborted (core dumped)

Help is greatly appreciated!

Was it helpful?

Solution

malloc(sizeof(tmp_name)) will allocate enough space to store one pointer. You then copy up to MAX_PATH_LEN bytes into that allocation, which is clearly wrong.

You should replace the sizeof(...) with a correct size calculation, probably 1 + strlen(...).

Also, strncpy will not null terminate the destination buffer if there is no null terminator within the first MAX_PATH_LEN bytes of tmp_name. This is probably a bug.

OTHER TIPS

This usually means that your heap data is corrupted, i.e. the data structures used by libc memory manager are corrupted. It is difficult to see what caused it (especially given only one function of the whole program.) Consider using a tool like dmalloc or a similar one to find the point at which your program corrupts the heap.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top