gpt4 book ai didi

c - sysmalloc 的 malloc 错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:04 25 4
gpt4 key购买 nike

我的 C 程序出现以下消息错误:

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

这个错误已经出现(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);
}

最佳答案

我想,你遇到了问题

 my_env[i] = NULL;

这是差一。可以使用的最大索引是

my_env[i-1] = NULL;

另请see why not to cast cmalloc() 和 family 的返回值。

关于c - sysmalloc 的 malloc 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31583542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com