473,406 Members | 2,633 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

segmentation fault on calloc

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 !
Nov 14 '05 #1
16 8943
laberth wrote:
I've got a segmentation fault on a calloc and I don'tunderstand why?
The simplest explanation I can think of is that you
may have forgotten '#include <stdlib.h>' which declares calloc().

Which reminds me:
A=(arbre)calloc(1,sizeof(struct noeud)); //segmentation fault just


In C programs, don't cast the result of malloc, calloc & co. It is not
necessary, and hides bugs like forgetting to declare calloc.
Anyway, if stdlib.h did not fix the problem, maybe the problem is
elsewhere - e.g., you modify some freed memory, which can corrupt
malloc's internal structures. If so, the following program should not
segfault, and you'll have to look for the problem elsewhere. A malloc
debugger like the commercial Purify or the free Elecetric Fence
(ftp://ftp.perens.com/pub/ElectricFence/) may detect the problem for
you.

#include <stdlib.h>

typedef struct noeud {
int val;
struct noeud *fgauche;
struct noeud *fdroit;
} *arbre;

arbre CreerNoeud(int valeur, arbre fg, arbre fd) {
arbre A;
A=calloc(1,sizeof(struct noeud));
A->val=valeur;
A->fgauche=fg;
A->fdroit=fd;
return A;
}

int main() {
(void) CreerNoeud(0, NULL, NULL);
return 0;
}

--
Hallvard
Nov 14 '05 #2
<la*****@voila.fr> wrote in message
news:84**************************@posting.google.c om...
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.
It's generally not considered good form to typedef pointers this way. Just
typedef the struct, leave the pointer (*) for the readability in the
subsequent declarations of struct noeud objects.

I.E. prefer...

arbre *A;

....over...

arbre A;
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.
I'm guessing you didn't include <stdlib.h>. I.e. you didn't supply a
function prototype for calloc().
A->val=valeur;
A->fgauche=fg;
A->fdroit=fd;
Not that calloc will properly initialise pointers to null anyway (at least
not portably), but since you clobber the zero-ed contents, why bother with
calloc? Why not just use...

A = malloc(sizeof *A);

If this fails to compile, then my guess was likely correct.
return A;
}


--
Peter
Nov 14 '05 #3
Peter Nilsson <ai***@acay.com.au> spoke thus:
Not that calloc will properly initialise pointers to null anyway (at least

^not

Just in case anyone was confused, although the rest of your sentence
indicates that you were not.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #4
Christopher Benson-Manica wrote:
Peter Nilsson <ai***@acay.com.au> spoke thus:

Not that calloc will properly initialise pointers to null anyway (at least


^not

Just in case anyone was confused, although the rest of your sentence
indicates that you were not.


I think he had it right, but it's a little confusing to see that idiom
written rather than spoken. In conversational English, I might say
something like, "Not that it will work, but you could try..." implying
that it may not work.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Nov 14 '05 #5
Kevin Goodsell <us*********************@neverbox.com> spoke thus:
I think he had it right, but it's a little confusing to see that idiom
written rather than spoken. In conversational English, I might say
something like, "Not that it will work, but you could try..." implying
that it may not work.


Curses, foil'd again ;( You're quite right, of course...

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #6
la*****@voila.fr wrote:

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


Don't use // comments in newsgroups, they don't wrap well!

Don't cast the result of malloc. It hides the error of failing to
#include <stdlib.h>

At any rate, by the time you get here there is no such thing as
"sizeof struct noeud". You never defined such. If you had used
the better and simpler form:

A = calloc(1, sizeof *A);

the problem would not arise.

WARNING: my guess is that you are using calloc to try to
initialize the gauche et droit pointers to NULL. This is NOT
valid. You should use explicit discrete initialization. You
should also test the allocation result. Thus the sequence would
become:

if (A = malloc(sizeof *A)) {
A->gauche = NULL; A->droit = NULL;
/* whatever */
}
else {
/* lack of memory action */
}

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #7
Hallvard B Furuseth <h.b.furuseth(nospam)@usit.uio(nospam).no> wrote in message news:<HB**************@bombur.uio.no>...
laberth wrote:
I've got a segmentation fault on a calloc and I don'tunderstand why?


The simplest explanation I can think of is that you
may have forgotten '#include <stdlib.h>' which declares calloc().

Failure to #include something is only going to confuse the compiler.
The linker doesn't care, and of course has no effect at runtime being
a preprocessor directive. A segmentation fault indicates a runtime
error.

Runtime errors are common on the C memory management API when the heap
was mismanaged in previous calls. free()ing a pointer twice is very
likely to cause a failure in the next malloc/calloc/realloc/etc call
because the call to free() is likely to (but may not) the heap in an
invalid state.

Many tools exist for debugging memory management. Start with Electric
Fence if you're still boggled by the failure. It will pinpoint the
location where the an over/underrun was made--before it segfaults

---
Jared Dykstra
http://www.bork.org/~jared
Nov 14 '05 #8
dy******@hotmail.com (Jared Dykstra) writes:
Hallvard B Furuseth <h.b.furuseth(nospam)@usit.uio(nospam).no> wrote in message news:<HB**************@bombur.uio.no>...
laberth wrote:
I've got a segmentation fault on a calloc and I don'tunderstand why?


The simplest explanation I can think of is that you
may have forgotten '#include <stdlib.h>' which declares calloc().


Failure to #include something is only going to confuse the compiler.
The linker doesn't care, and of course has no effect at runtime being
a preprocessor directive. A segmentation fault indicates a runtime
error.


Failure to #include <stdlib.h> makes the compiler believe that `calloc'
returns `int', while in fact it returns `void *'. Normally the compiler
would emit a diagnostic when an `int' is assigned to a pointer, however
the OP prevented this by casting the return value of `calloc'. The result
is undefined behavior, which may well cause a runtime error.

Martin
Nov 14 '05 #9
Martin Dickopp <ex****************@zero-based.org> wrote in message news:<bs*************@news.t-online.com>...
dy******@hotmail.com (Jared Dykstra) writes:
Hallvard B Furuseth <h.b.furuseth(nospam)@usit.uio(nospam).no> wrote in message news:<HB**************@bombur.uio.no>...
laberth wrote:

> I've got a segmentation fault on a calloc and I don'tunderstand why?

The simplest explanation I can think of is that you
may have forgotten '#include <stdlib.h>' which declares calloc().


Failure to #include something is only going to confuse the compiler.
The linker doesn't care, and of course has no effect at runtime being
a preprocessor directive. A segmentation fault indicates a runtime
error.


Failure to #include <stdlib.h> makes the compiler believe that `calloc'
returns `int', while in fact it returns `void *'. Normally the compiler
would emit a diagnostic when an `int' is assigned to a pointer, however
the OP prevented this by casting the return value of `calloc'. The result
is undefined behavior, which may well cause a runtime error.

Martin


True, but only if sizeof(int) != sizeof(void *). This is, of course,
entirely possible.

Given that the original poster said:
"I also tried A=(arbre)calloc(1,sizeof(struct noeud));
and
A=(arbre*)calloc(1,sizeof(struct noeud));"

It is clear he is not too familiar with calloc() and/or dynamic memory
management.

---
Jared Dykstra
http://www.bork.org/~jared
Nov 14 '05 #10
dy******@hotmail.com (Jared Dykstra) writes:

R> Martin Dickopp <ex****************@zero-based.org> wrote in message news:<bs*************@news.t-online.com>...
dy******@hotmail.com (Jared Dykstra) writes:
Hallvard B Furuseth <h.b.furuseth(nospam)@usit.uio(nospam).no> wrote in message news:<HB**************@bombur.uio.no>...
> laberth wrote:
>
> > I've got a segmentation fault on a calloc and I don'tunderstand why?
>
> The simplest explanation I can think of is that you
> may have forgotten '#include <stdlib.h>' which declares calloc().

Failure to #include something is only going to confuse the compiler.
The linker doesn't care, and of course has no effect at runtime being
a preprocessor directive. A segmentation fault indicates a runtime
error.


Failure to #include <stdlib.h> makes the compiler believe that `calloc'
returns `int', while in fact it returns `void *'. Normally the compiler
would emit a diagnostic when an `int' is assigned to a pointer, however
the OP prevented this by casting the return value of `calloc'. The result
is undefined behavior, which may well cause a runtime error.


True, but only if sizeof(int) != sizeof(void *).


No, even if sizeof(int) == sizeof(void *), the behavior remains undefined.
For example, return values of type `int' might be returned in a different
register than return values of pointer type.

Martin
Nov 14 '05 #11
Jared Dykstra wrote:
Martin Dickopp <ex****************@zero-based.org> wrote in message news:<bs*************@news.t-online.com>...
dy******@hotmail.com (Jared Dykstra) writes:

Hallvard B Furuseth <h.b.furuseth(nospam)@usit.uio(nospam).no> wrote in message news:<HB**************@bombur.uio.no>...

laberth wrote:
>I've got a segmentation fault on a calloc and I don'tunderstand why?

The simplest explanation I can think of is that you
may have forgotten '#include <stdlib.h>' which declares calloc().

Failure to #include something is only going to confuse the compiler.
The linker doesn't care, and of course has no effect at runtime being
a preprocessor directive. A segmentation fault indicates a runtime
error.
Failure to #include <stdlib.h> makes the compiler believe that `calloc'
returns `int', while in fact it returns `void *'. Normally the compiler
would emit a diagnostic when an `int' is assigned to a pointer, however
the OP prevented this by casting the return value of `calloc'. The result
is undefined behavior, which may well cause a runtime error.

Martin

True, but only if sizeof(int) != sizeof(void *).


Chapter and Verse, please.
This is, of course,
entirely possible.


Indeed, but to the best of my knowledge this is not the only thing that
could cause a program containing the construct in question to fail - it
just happens to be the most likely thing.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Nov 14 '05 #12
la*****@voila.fr writes:
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.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)
Nov 14 '05 #13
On Tue, 30 Dec 2003 20:19:06 UTC, dy******@hotmail.com (Jared Dykstra)
wrote:
True, but only if sizeof(int) != sizeof(void *). This is, of course,
entirely possible.
Hm, there is nothing that forbids a compiler to define a calling
interace such as:

return int type in R6
return floating point type in G0
return pointer type in RY

That defines 3 different memory locations. So when the compiler misses
the prototype of malloc/calloc.... it sees 'function returns result in
R6, so get content of R6, convert it to pointer and assign it to dest.

But R6 contains something bot not a valid pointer!
Given that the original poster said:
"I also tried A=(arbre)calloc(1,sizeof(struct noeud));
and
A=(arbre*)calloc(1,sizeof(struct noeud));"

It is clear he is not too familiar with calloc() and/or dynamic memory
management.

---
Jared Dykstra
http://www.bork.org/~jared

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #14
On Mon, 29 Dec 2003 15:32:53 UTC, "Peter Nilsson" <ai***@acay.com.au>
wrote:
<la*****@voila.fr> wrote in message
news:84**************************@posting.google.c om...
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.
It's generally not considered good form to typedef pointers this way. Just
typedef the struct, leave the pointer (*) for the readability in the
subsequent declarations of struct noeud objects.


Yes, no. A more common practise is to write user defined types in
uppercase only to destinict them clearly from natural types.
I.E. prefer...

arbre *A;

...over...

arbre A;


ARBE a; /* a struct, type is only defined */
/* if there is a need to define */
/* a struct statically */
PARBRE pa; /* a pointer to a struct */
--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #15
On Mon, 29 Dec 2003 14:59:02 UTC, la*****@voila.fr wrote:
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.
2 possible errors:

1. You've forgotten to #include <stdlib.h>. This causes undefined
behavior

2. some kind of UB before you enters the function that causes the
fault.
In special: somewhere in your program you've written into memory that
is owned by the malloc management itsef; You've destroyed the memory
allocation management data.
At least malloc(), calloc() can fail every time because it is unable
to return the required amount of memory. This is flagged as returnin a
NULL pointer. You're obligeted to test for this in any case.
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 !


All sayed above.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #16
The Real OS/2 Guy wrote:
On Mon, 29 Dec 2003 15:32:53 UTC, "Peter Nilsson" <ai***@acay.com.au>
wrote:
<la*****@voila.fr> wrote in message
news:84**************************@posting.google .com...
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.


It's generally not considered good form to typedef pointers this way. Just
typedef the struct, leave the pointer (*) for the readability in the
subsequent declarations of struct noeud objects.


Yes, no. A more common practise is to write user defined types in
uppercase only to destinict them clearly from natural types.


That's another subject. It's one common practice, certainly.
Another is to give them an uppercase initial letter.

But - preferably as typedefs for a struct or something, not for a
pointer to a struct. Code which uses pointer typedefs is often harder
to read than other code. E.g. a function argument declaration will have
no '*', so one cannot see that the argument is a pointer argument and
thus a 'read/write' argument, it looks like a read-only argument.

--
Hallvard
Nov 14 '05 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Narendran Kumaraguru Nathan | last post by:
Hi all, I am fairly experianced in C. I am writing a program in which I'm getting a segmentation fault. The problem is that it is getting the segmentation fault when executing calloc. I tried...
5
by: Fra-it | last post by:
Hi everybody, I'm trying to make the following code running properly, but I can't get rid of the "SEGMENTATION FAULT" error message when executing. Reading some messages posted earlier, I...
19
by: Sameer | last post by:
Hi friends, I am using Mandriva Linux 9.2 and gcc. My source code is, int chunkin ; //no error int i ; for (i=0;i<7225;i++) { chunkin = somedata ;
3
by: madunix | last post by:
My Server is suffering bad lag (High Utlization) I am running on that server Oracle10g with apache_1.3.35/ php-4.4.2 Web visitors retrieve data from the web by php calls through oci cobnnection...
2
by: ramu | last post by:
Hi, While am trying to run this code am getting segmentation fault. What's wrong with this code? Here am trying to assign a value to the variable b. #define SIZE 10 struct y { int a;...
14
by: Vlad Dogaru | last post by:
Hello, I am trying to learn C, especially pointers. The following code attempts to count the appearences of each word in a text file, but fails invariably with Segmentation Fault. Please help me...
1
by: samac | last post by:
Hi all, Need some help in c. I have not been in programming for ten years. Here is my problem: From main(), I call a function - a_function(). In a_function(), I call another function...
5
by: lancer6238 | last post by:
Dear all, I'm trying to implement the Smith-Waterman algorithm for DNA sequence alignment. I'm aligning a 2040 bp query sequence against a 5040 bp sequence. I'll be trying to implement a parallel...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.