2
votes

I get the following message error with my C program :

a.out: 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.

zsh: abort (core dumped) ./a.out

This error has already been raised (here), memory has been corrupted. But can anyone tell me what in my programm causes this error ? (the programm crash when I call strdup for the first time)

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

char    **cp_env(char **env)
{
    int i;
    char **my_env;

//  Count env size
    i = 0;
    while (env[i])
        i++;

// Malloc env copy
    if (!(my_env = (char**)malloc(sizeof(char*) * i)))
        exit(-1);
    my_env[i] = NULL;

// copy env
    while (i--)
        my_env[i] = strdup(env[i]);

    return(my_env);
}

int         main(int ac, char **av, char **env)
{
    char**  my_env;

    my_env = cp_env(env);

    printf("%s", my_env[0]);

//  free

    return (0);
}
1

1 Answers

2
votes

I think, you're facing problem in

 my_env[i] = NULL;

This is off-by-one. The maximum index that can be used is

my_env[i-1] = NULL;

Also, please see why not to cast the return value of malloc() and family in C.