Reputation: 83
I had this line of code :
conf->table = malloc(sizeof(struct Categorie)*(csv_nbLines(filename)));
that led to a bug when calling free()
on conf
because struct Categorie
include a string (array of char
s).
I fixed the bug by replacing the sizeof(struct Categorie)
with 30
because I know the said string will not go over 30 bytes.
Is this acceptable ? If not what would be a better way to malloc
the exact amount of memory needed ?
EDIT :
struct Categorie {
char *name;
char c;
};
EDIT2 :
I end up with this and it works perfectly (the names speaks for themselves).
in conf_init()
conf->table = malloc(sizeof(struct Categorie))
in conf_load()
where pch
is a string returned by strtok()
conf->table[i].name = malloc(sizeof(char)*strlen(pch));
conf->table[i].name = pch;
I hope this is enough explanation for the next one :)
Upvotes: 1
Views: 235
Reputation: 8589
Answer: No. That is not acceptable.
You need to provide more code to understand what is going on, but assuming conf->table
is struct Categorie *
then there's something pretty rotten.
If that isn't the type then it's not clear why you ever thought sizeof(struct Categorie)
might be the answer.
Upvotes: 1
Reputation: 134336
I'm afraid, NO.
Assuming the string you mentioned is in form of
struct Categorie
{
.
.
char * str;
}
You're supposed to first malloc()
the memory for conf->table
with sizeof(struct Categorie)
, and then, malloc()
for conf->table->str
.
Not to mention, free()
ing also required, in the exact opposite oreder of allocation, i.e, first you need to free conf->table->str
and then conf->table
.
Upvotes: 4