gpt4 book ai didi

c - malloc 问题 (77128,0x7fffb99573c0) malloc : *** error for object 0x7fd77c4025c8:

转载 作者:行者123 更新时间:2023-11-30 16:15:31 25 4
gpt4 key购买 nike

我有关于 malloc 的作业要做,并且遇到了问题。

我必须将 av 中作为字符串数组给出的内容放入如下结构中:

typedef struct s_stock_str
{
int size; // the size of the string
char *str; // the string
char *copy; // a copie of the string
} s_stock_str;

问题是我计算了数组中链所具有的所有字符,并将其分配给以下形式的指针:

lentstr = ((lentstr + ac -1) * 2 + ((ac -1 )*sizeof(int)));
pointeur = malloc((sizeof(char) * lentstr));

lentstr + ac -1 表示“\0”的空格
*2为副本的位置
((ac -1 )*sizeof(int)) 表示 int 的大小

我将所有内容乘以字符的大小。
ac 是参数的数量,我们不使用第一个参数,所以我输入 -1。

我分配了所有东西,但在第一个参数之后它给了我这个错误:

a.out(77128,0x7fffb99573c0) malloc: * error for object 0x7fd77c4025c8: incorrect checksum for freed object - object was probably modified after being freed. * set a breakpoint in malloc_error_break to debug

谁能给我解释一下这是什么?

int     taille(int ac, char **av)
{
int i;
int a;
int compteur;

compteur = 0;
i = 0;
a = 1;
while(a < ac )
{
i = 0;
while(av[a][i++])
compteur++;
a++;
}
return (compteur);
}

struct s_stock_str *ft_strs_to_tab(int ac, char **av)
{
s_stock_str *pointeur;
int lentstr;
int i;
int size;

lentstr = taille(ac, av);
lentstr = ((lentstr + ac -1) * 2 + ((ac -1 )*sizeof(int)));
pointeur = malloc((sizeof(char) * lentstr));
i = 1;
while (i < ac)
{
size = tailletableau(av[i],i);
pointeur[i].size = size;
pointeur[i].str = av[i];
pointeur[i].copy = copie(av[i],size, i);
i++;
}
return pointeur;
}

最佳答案

s_stock_str *pointeur;
...
pointeur[i].size = size;
...

如果i > 1,那么您肯定正在写入未分配的内存(您仅为一个元素malloc分配了内存)。

<小时/>

另外,这个:

i = 1;
while (i < ac)
{
size = tailletableau(av[i],i);
pointeur[i].size = size;
pointeur[i].str = av[i];
pointeur[i].copy = copie(av[i],size, i);
i++;
}

应该写成for(为了简单性和可读性):

for( i = 1; i < ac; i++)
{
size = tailletableau(av[i],i);
pointeur[i].size = size;
pointeur[i].str = av[i];
pointeur[i].copy = copie(av[i],size, i);
}

关于c - malloc 问题 (77128,0x7fffb99573c0) malloc : *** error for object 0x7fd77c4025c8:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57066910/

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