I have homework to do with malloc and have an issue.
I have to take what is given as a array of string in av and put it in a structure that goes like this:
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;
The problem is that I count all the characters that the chain in the array have and malloc it to a pointer in this form:
lentstr = ((lentstr + ac -1) * 2 + ((ac -1 )*sizeof(int)));
pointeur = malloc((sizeof(char) * lentstr));
lentstr + ac -1 for the space of '\0'
*2 for the place of the copy
((ac -1 )*sizeof(int)) for the size of the int
and I multiply everything with the size of a char.
ac is the number of arguments and we don't use the first one so I put -1.
I malloc everything but after first argument it give me this error:
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
Could someone explain to me what is this ?
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;
}
malloc(sizeof(struct s_stock_str) * ac)to get chunk of memory that can hold ac of the type struct s_stock_str - Clayton Ls_stock_strelements and index it up to the valueac-1, you should be allocatingpointeur = malloc(sizeof(s_stock_str) * ac);. Also, you have not shown what thecopiefunction does. - paddy