I've got a segmentation fault on a calloc and I don'tunderstand why?
Here is what I use :
typedef struct noeud {
int val;
struct noeud *fgauche;
struct noeud *fdroit;
} *arbre; //for those who don't speak french arbre means tree.
An this is the fonction where I use the calloc :
arbre CreerNoeud(int valeur, arbre fg, arbre fd){
arbre A;
A=(arbre)calloc(1,sizeof(struct noeud)); //segmentation fault just
here.
A->val=valeur;
A->fgauche=fg;
A->fdroit=fd;
return A;
}
I also tried A=(arbre)calloc(1,sizeof(struct noeud));
and
A=(arbre*)calloc(1,sizeof(struct noeud));
but it doesn't work. Help me please !
Others have pointed out several errors (casting the result of
calloc(), possibly omitting "#include <stdlib.h>"), as well as some
style issues, but none of those is likely to cause a segmentation
fault on the calloc() call.
Failing to include <stdlib.h> will probably make the compiler assume
that calloc() returns an int rather than a void*; casting the result
to type arbre (a pointer to struct noeud) forces the phony int to be
converted to a pointer. This invokes undefined behavior, but the
effect is most likely to be one of two things. If an int and a struct
pointer happen to be the same size, and happen to be returned from
functions in the same way (this is fairly common), the call will
likely work as expected. If the types are of different sizes, or are
returned differently (in different registers, for example), you'll
probably assign a garbage value to A, but you're unlikely to get a
segmentation fault until you try to use the value.
Add "#include <stdlib.h>" to the top of your program if you haven't
already. Use malloc() rather than calloc() (since you assign values
to all the members of the struct, there's no need to zero it when you
allocate it). Check the value returned by malloc(); if you're running
out of memory, it will return a null pointer. Don't cast the value
returned by malloc().
Fix the problems that have been pointed out and try again. If you're
still having problems, post a small self-contained program that
exhibits the problem, and we'll take another look at it. Don't post a
program fragment; you're likely to delete the code that's actually
causing the problem. Cut-and-paste the exact code that you compiled;
if you try to re-type it into your news client, any typos could mask
the actual problem.
There's a good chance that going through this exercise will lead you
to fix the problem yourself. If not, we'll be glad to help.