【发布时间】:2015-10-13 12:47:52
【问题描述】:
我的 C 程序出现以下消息错误:
a.out: malloc.c:2369: sysmalloc: 断言`(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)' 失败。
zsh: abort (核心转储)./a.out
这个错误已经出现(here),内存已经损坏。但是谁能告诉我我的程序中是什么导致了这个错误? (第一次调用strdup时程序崩溃)
#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);
}
【问题讨论】: