473,378 Members | 1,209 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,378 software developers and data experts.

malloc trouble

ncf
Hi all.

In another topic, I was informed that I had to dynamically allocate
memory instead of just trying to expand on a list. (I'm trying to learn
C, and have a strong background in PHP and Python) In light of that, I
have been trying to learn malloc, realloc, and free, but to no avail.

But for some reason, I'm getting segfaults right and left, and to be
honest, I am not having any luck at all really in finding out why it
isn't working. However, I have traced it and discovered that the
malloc() call is what is causing the problem. (traced by adding various
printf()s and then moving the malloc to it's own line)

It would be greatly appreciated if anyone can point out what the heck
I'm doing so wrong. Code snipplets are included at the end of this
message.

Thank you soo much in advance.

-Wes

/* at the "file" level */
#define BUFFLEN 100
char **messages;
int num_messages=0;
/* inside of main() */
if ( (messages[num_messages] = (char *)malloc((size_t)BUFFLEN))
==NULL)
{
printf("Could not allocate space.\n");
return 1;
}

Nov 15 '05 #1
27 1890
ncf wrote:
Hi all.

In another topic, I was informed that I had to dynamically allocate
memory instead of just trying to expand on a list. (I'm trying to learn
C, and have a strong background in PHP and Python) In light of that, I
have been trying to learn malloc, realloc, and free, but to no avail.

But for some reason, I'm getting segfaults right and left, and to be
honest, I am not having any luck at all really in finding out why it
isn't working. However, I have traced it and discovered that the
malloc() call is what is causing the problem. (traced by adding various
printf()s and then moving the malloc to it's own line)

It would be greatly appreciated if anyone can point out what the heck
I'm doing so wrong. Code snipplets are included at the end of this
message.

Thank you soo much in advance.

-Wes

/* at the "file" level */
#define BUFFLEN 100
char **messages;
[In the future post *real* *compilable* code. It makes things easier.]

What's the value of `messages' at his point?
int num_messages=0;
/* inside of main() */
if ( (messages[num_messages] = (char *)malloc((size_t)BUFFLEN))
==NULL)
{
printf("Could not allocate space.\n");
return 1;
}

Please see the FAQ, particularly the piece on `dynamic allocation of
multidimensional arrays'.

HTH,
--ag

--
Artie Gold -- Austin, Texas
http://goldsays.blogspot.com (new post 8/5)
http://www.cafepress.com/goldsays
"If you have nothing to hide, you're not trying!"
Nov 15 '05 #2
ncf
Alrighty, I just checked one comp.lang.c faq (located at
http://www.faqs.org/faqs/C-faq/faq/), and to be quite honest, the code
they're using is making little sense to me, but I will give it a shot.

And, even though it may or may not be necessary until I get the chance
to add the pointer allocation, the code is currently as follows:
/*
* malloc/realloc/free test
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define BUFFLEN 10

char **messages;
int num_messages=0;

int main(int argc, char **argv) {
char tmpmsg[][BUFFLEN] = {"a","b","c","d","e"};
int tmpnum = sizeof(tmpmsg)/BUFFLEN;

printf("Going to copy %d messages.\n",tmpnum);

/* Do the copy loop */
int x;
for (x=0; x<tmpnum; x++) {
printf("Allocating space for %d.\n",x);
if ( (messages[num_messages] = (char *)malloc((size_t)BUFFLEN))
==NULL)
{
printf("Could not allocate space.\n");
return 1;
}

strcpy(messages[num_messages], tmpmsg[x]);
num_messages++;
}

/* print all the values */
for (x=0;x<num_messages;x++) {
printf("%02d => %s\n",x,messages[x]);
}

/* clear and free all the positions of memory */
for (x=num_messages-1;x>=0;x--) {
memset(messages[x], '\0', sizeof(messages[x]));
free(messages[x]);
}

/* the end of the test...finally :P */
return 0;
}

Nov 15 '05 #3
ncf
Ok, wow, I think I get it now, but it would be grealy appreciated if
someone could look over my updated/modified code to make sure that it
does as it seems it should. Thank you for pointing out the obvious
(faq)--some days I deserve to be slapped :P

-Wes

/*
* malloc/realloc/free test
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define BUFFLEN 10

char **messages;
int num_messages=0;

int main(int argc, char **argv) {
char tmpmsg[][BUFFLEN] = {"a","b","c","d","e"};
int tmpnum = sizeof(tmpmsg)/BUFFLEN;

printf("Going to copy %d messages.\n",tmpnum);

/* first, malloc 0*sizeof(char *) bytes for messages, as we have no
pointers yet */
messages = malloc(num_messages*sizeof(char *));

/* Do the copy loop */
int x;
for (x=0; x<tmpnum; x++) {
printf("Allocating space for %d.\n",x);
if ( (messages = realloc(messages, (num_messages+1)*sizeof(char *)))
== NULL)
{
printf("Could not allocate space for one more pointer.\n");
return 1;
}
if ( (messages[num_messages] = (char *)malloc((size_t)BUFFLEN))
==NULL)
{
printf("Could not allocate space.\n");
return 1;
}

strcpy(messages[num_messages], tmpmsg[x]);
num_messages++;
}

/* print all the values */
for (x=0;x<num_messages;x++) {
printf("%02d => %s\n",x,messages[x]);
}

/* clear and free all the positions of memory */
for (x=num_messages-1;x>=0;x--) {
memset(messages[x], '\0', sizeof(messages[x]));
free(messages[x]);
}
free(messages);

/* the end of the test...finally :P */
return 0;
}

Nov 15 '05 #4
>But for some reason, I'm getting segfaults right and left, and to be
honest, I am not having any luck at all really in finding out why it
isn't working. However, I have traced it and discovered that the
malloc() call is what is causing the problem. (traced by adding various
printf()s and then moving the malloc to it's own line)

It would be greatly appreciated if anyone can point out what the heck
I'm doing so wrong. Code snipplets are included at the end of this
message.

Thank you soo much in advance.

-Wes

/* at the "file" level */
#define BUFFLEN 100
char **messages;
int num_messages=0;
/* inside of main() */
You may not assign to messages[num_messages] until you
have assigned something to messages (and something other
than NULL), which you don't show here.
if ( (messages[num_messages] = (char *)malloc((size_t)BUFFLEN))
==NULL)
{
printf("Could not allocate space.\n");
return 1;
}


Gordon L. Burditt
Nov 15 '05 #5
ncf wrote:
Ok, wow, I think I get it now, but it would be grealy appreciated if
someone could look over my updated/modified code to make sure that it
does as it seems it should. Thank you for pointing out the obvious
(faq)--some days I deserve to be slapped :P

-Wes
You're obviously new around here. *That* was no slap! ;-)

/*
* malloc/realloc/free test
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define BUFFLEN 10

char **messages;
int num_messages=0;

int main(int argc, char **argv) {
char tmpmsg[][BUFFLEN] = {"a","b","c","d","e"};
int tmpnum = sizeof(tmpmsg)/BUFFLEN;

printf("Going to copy %d messages.\n",tmpnum);

/* first, malloc 0*sizeof(char *) bytes for messages, as we have no
pointers yet */
messages = malloc(num_messages*sizeof(char *));
Why bother? Leave this line out.
/* Do the copy loop */
int x;
for (x=0; x<tmpnum; x++) {
printf("Allocating space for %d.\n",x);
if ( (messages = realloc(messages, (num_messages+1)*sizeof(char *)))
== NULL)
Though it's not applicable here (as receiving a NULL from realloc will
lead to an immediate exit, as per the code below), you should assign the
return value of realloc() to a temporary variable, just in case it
fails. Otherwise (assuming your program can continue) you've created a
memory leak as you've lost the pointer to the original buffer.

Also, instead of using `sizeof (char *)' use `sizeof *messages'; it's a
style issue, to be sure (and not immediately important here) but it
helps in cases where the type you're allocating may change [it's always
preferable to have to make as few changes as possible when something,
well, changes.]
{
printf("Could not allocate space for one more pointer.\n");
return 1;
}
if ( (messages[num_messages] = (char *)malloc((size_t)BUFFLEN))
==NULL) Don't cast the return value of malloc(). It's unnecessary and can hide
errors. {
printf("Could not allocate space.\n");
return 1;
}

strcpy(messages[num_messages], tmpmsg[x]);
num_messages++;
}

/* print all the values */
for (x=0;x<num_messages;x++) {
printf("%02d => %s\n",x,messages[x]);
}

/* clear and free all the positions of memory */
for (x=num_messages-1;x>=0;x--) {
memset(messages[x], '\0', sizeof(messages[x]));
Why bother? You're just about to free the space anyway!
free(messages[x]);
}
free(messages);

/* the end of the test...finally :P */
return 0;
}

You're getting there.

Cheers and HTH,
--ag

--
Artie Gold -- Austin, Texas
http://goldsays.blogspot.com (new post 8/5)
http://www.cafepress.com/goldsays
"If you have nothing to hide, you're not trying!"
Nov 15 '05 #6
ncf
I definately chopped this up to shrink it down quite a bit, but yea, my
replies are inline.

Artie Gold wrote:
Thank you for pointing out the obvious (faq)--some days I deserve to
be slapped :P You're obviously new around here. *That* was no slap! ;-)

Hehe, no, but I practically slapped myself over some of the stupid
errors I've done. :grin:

messages = malloc(num_messages*sizeof(char *));

Why bother? Leave this line out.

Hmm...how would I do the realloc later then if the space was never
alloc'd? Or would that be unnecessary as well? :slightly confused:

if ( (messages = realloc(messages, (num_messages+1)*sizeof(char *))) == NULL)

Though it's not applicable here (as receiving a NULL from realloc will
lead to an immediate exit, as per the code below), you should assign the
return value of realloc() to a temporary variable, just in case it
fails. Otherwise (assuming your program can continue) you've created a
memory leak as you've lost the pointer to the original buffer.

Hmm...I *think* I see what you're saying. By memory leak, I'm infering
that you mean memory that was never free()d for other applications to
use.

Also, instead of using `sizeof (char *)' use `sizeof *messages'; it's a
style issue, to be sure (and not immediately important here) but it
helps in cases where the type you're allocating may change [it's always
preferable to have to make as few changes as possible when something,
well, changes.] Heh, alrighty :) I'll try to keep that in mind next time so you don't
kill me (JPJP)

if ( (messages[num_messages] = (char *)malloc((size_t)BUFFLEN)) ==NULL)

Don't cast the return value of malloc(). It's unnecessary and can hide
errors.

Hmm...I'm not too sure right now how it'd hide errors, but hey! It'll
make sense probably later on, so lets not worry too much about that.
I'll just take your word for it ;)

memset(messages[x], '\0', sizeof(messages[x]));

Why bother? You're just about to free the space anyway!

Eh, I'm one of those odd people that likes to clean stuff up after
usage. But in retrospect, wasted CPU (however little).

You're getting there.

Horray :P /Rand
Thanks AG and have a GREAT day :)
-Wes

Nov 15 '05 #7
ncf wrote:
Artie Gold wrote:
messages = malloc(num_messages*sizeof(char *));


Why bother? Leave this line out.


Hmm...how would I do the realloc later then if the space was never
alloc'd? Or would that be unnecessary as well? :slightly confused:


realloc(NULL, size) does the same thing as malloc(size),
realloc(ptr, 0) does the same thing as free(ptr).
Your implementation typically comes with a standard library
reference which you should look into; if not, try the C99
library reference on dinkumware.com
if ( (messages = realloc(messages, (num_messages+1)*sizeof(char *))) == NULL)


Though it's not applicable here (as receiving a NULL from realloc will
lead to an immediate exit, as per the code below), you should assign the
return value of realloc() to a temporary variable, just in case it
fails. Otherwise (assuming your program can continue) you've created a
memory leak as you've lost the pointer to the original buffer.


Hmm...I *think* I see what you're saying. By memory leak, I'm infering
that you mean memory that was never free()d for other applications to
use.


Yes and no. It may be also memory _you_ cannot use later on in
your program because you already allocated but sort of lost the
key to use it. If you need large amounts of memory this may be
the bit which makes your program exit earlier than planned due
to (self-inflicted) lack of memory...
As an aside, most modern operating systems clean up after an
application finished, so many well-known applications accept
that there are memory leaks in their code that could not be
tracked down. This is bad practice and may hide other errors
which then come down as soon as some minor detail changes. Just
avoid them :-)

if ( (messages[num_messages] = (char *)malloc((size_t)BUFFLEN)) ==NULL)


Don't cast the return value of malloc(). It's unnecessary and can hide
errors.


Hmm...I'm not too sure right now how it'd hide errors, but hey! It'll
make sense probably later on, so lets not worry too much about that.
I'll just take your word for it ;)


For one, it is not necessary. The other thing is that casts
are pretty strong: They tell the compiler to shut up.
In combination with the "implicit int" rule, this may shadow
the fact that you forgot to #include <stdlib.h> which in turn
can lead to odd effects if sizeof(int) is different from the
size of the respective pointer type you cast to -- it may go
well 99% of the time but every now and then, you have your
program eating your hard disc's contents or similar...

You're getting there.


Horray :P /Rand

Thanks AG and have a GREAT day :)


My, you _really_ have promise ;-)
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 15 '05 #8
ncf <no***************@gmail.com> wrote:
Alrighty, I just checked one comp.lang.c faq (located at
http://www.faqs.org/faqs/C-faq/faq/), and to be quite honest, the code
they're using is making little sense to me, but I will give it a shot.
It is proper Usenet etiquette to include the text you are replying to.
To do this using Google groups, please follow the instructions below,
penned by Keith Thompson:

If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.
if ( (messages[num_messages] = (char *)malloc((size_t)BUFFLEN))


It isn't in the FAQ, but should be: Casting the return of malloc() is
both unnecessary and inadvisable. Read this group's archives for
details.

--
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 15 '05 #9
"ncf" <no***************@gmail.com> writes:
Ok, wow, I think I get it now, but it would be grealy appreciated if
someone could look over my updated/modified code to make sure that it
does as it seems it should. Thank you for pointing out the obvious
(faq)--some days I deserve to be slapped :P
Here is my take: Your code is fine, only minor issues.

-Wes

/*
* malloc/realloc/free test
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define BUFFLEN 10

char **messages;
char **messages = NULL; /* initalize, so we can use realloc from start */
int num_messages=0;

int main(int argc, char **argv) {
int main(void) { /* here we don't use command line arguments, so void
eliminates a couple of warnings */
char tmpmsg[][BUFFLEN] = {"a","b","c","d","e"};
int tmpnum = sizeof(tmpmsg)/BUFFLEN;

printf("Going to copy %d messages.\n",tmpnum);

/* first, malloc 0*sizeof(char *) bytes for messages, as we have no
pointers yet */
/* Remove this:
messages = malloc(num_messages*sizeof(char *));
*/

/*
* I (and many with me) prefer the style: ptr = malloc(count * sizeof *ptr);
* That works all the time, is always the same (you don't need to think of the
* type at all), but here you don't need malloc at all, since you don't need
* any memory yet, but just a defined starting point for later calls to realloc.
* Setting messages = NULL is enough. (Calling realloc with a NULL ptr is
* exactly the same as calling malloc).
*/

/* Do the copy loop */
{ /* in C90 variable declarations must only appear before executable code
this has changed in C99, but must people still use C90 compilers */
int x;
for (x=0; x<tmpnum; x++) {
printf("Allocating space for %d.\n",x);
if ( (messages = realloc(messages, (num_messages+1)*sizeof(char *)))
== NULL)
/* Style: */ messages = realloc(messages, num_messages + 1 * sizeof *messages);

/* Also notice that if you need somewhat more sofisiticated error handling
* you lose the original buffer if realloc fails. In that case you need to do
* something like:
* tmp = realloc(...);
* if (tmp == NULL) {
* error_handling(...);
* free(messages) /* or maybe not, depending on everything else */
* return, abort, exit or something perhaps
* }
* messages = tmp;
*/
{
printf("Could not allocate space for one more pointer.\n");
return 1;
return EXIT_FAILURE; /* Only defined return codes from main are
0, EXIT_OK, and EXIT_FAILURE */
}
if ( (messages[num_messages] = (char *)malloc((size_t)BUFFLEN))
==NULL)
/* Unnecessary casts, I'd say: */
if ((message[num_messages] = malloc(BUFFLEN)) == NULL)

{
printf("Could not allocate space.\n");
return 1;
return EXIT_FAILURE;
}

strcpy(messages[num_messages], tmpmsg[x]);
num_messages++;
}

/* print all the values */
for (x=0;x<num_messages;x++) {
printf("%02d => %s\n",x,messages[x]);
}

/* clear and free all the positions of memory */
for (x=num_messages-1;x>=0;x--) {
memset(messages[x], '\0', sizeof(messages[x]));
free(messages[x]);
}
free(messages);
} /* end of local block for int x; */

/* the end of the test...finally :P */
return 0;
}

Nov 15 '05 #10

"Christopher Benson-Manica" <at***@nospam.cyberspace.org> wrote in message
news:di**********@chessie.cirr.com...
ncf <no***************@gmail.com> wrote:
Alrighty, I just checked one comp.lang.c faq (located at
http://www.faqs.org/faqs/C-faq/faq/), and to be quite honest, the code
they're using is making little sense to me, but I will give it a shot.


It is proper Usenet etiquette to include the text you are replying to.
To do this using Google groups, please follow the instructions below,
penned by Keith Thompson:

If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.
if ( (messages[num_messages] = (char
*)malloc((size_t)BUFFLEN))


It isn't in the FAQ, but should be: Casting the return of malloc() is
both unnecessary and inadvisable.


http://www.eskimo.com/~scs/C-faq/q7.6.html
http://www.eskimo.com/~scs/C-faq/q7.7.html

These don't go into much detail, but they're in there. :-)

-Mike
Nov 15 '05 #11
Mike Wahler <mk******@mkwahler.net> wrote:
http://www.eskimo.com/~scs/C-faq/q7.6.html
http://www.eskimo.com/~scs/C-faq/q7.7.html These don't go into much detail, but they're in there. :-)


I'm aware of those, but neither explicitly says "don't do it", which
is a sentence that needs to be culled from the thousands of posts on
the subject and enshrined in the FAQ :-)

--
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 15 '05 #12
Niklas Norrthon wrote:
"ncf" <no***************@gmail.com> writes:
<snip>
/*
* malloc/realloc/free test
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define BUFFLEN 10

char **messages;


char **messages = NULL; /* initalize, so we can use realloc from start */


It's declared at file scope so it will be initialised to a null pointer
anyway. However, if the variables were moved in to main (which would be
better style since using globals where they are not needed is bad style
and a very bad habit, then it would need initialising.
int num_messages=0;

int main(int argc, char **argv) {


int main(void) { /* here we don't use command line arguments, so void
eliminates a couple of warnings */


<snip>
return EXIT_FAILURE; /* Only defined return codes from main are
0, EXIT_OK, and EXIT_FAILURE */


I think you mean EXIT_SUCCESS rather than EXIT_OK. It should also be
noted that returning 0 is defined as meaning success.

<snip>
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #13
ncf
Alrighty, yea, I didn't know how to reply w/ quoting for a bit out of
my own stupidity, but thanks for pointing out how ;P

I'll keep it in mind not to cast malloc()'s return

Thanks :)

Christopher Benson-Manica wrote:
ncf <no***************@gmail.com> wrote:
Alrighty, I just checked one comp.lang.c faq (located at
http://www.faqs.org/faqs/C-faq/faq/), and to be quite honest, the code
they're using is making little sense to me, but I will give it a shot.


It is proper Usenet etiquette to include the text you are replying to.
To do this using Google groups, please follow the instructions below,
penned by Keith Thompson:

If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.
if ( (messages[num_messages] = (char *)malloc((size_t)BUFFLEN))


It isn't in the FAQ, but should be: Casting the return of malloc() is
both unnecessary and inadvisable. Read this group's archives for
details.

--
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 15 '05 #14
ncf
Flash Gordon wrote:
However, if the variables were moved in to main (which would be
better style since using globals where they are not needed is bad style
and a very bad habit, then it would need initialising.


The code I'm working with right now has messages and num_messages in
the file scope because I'm going to be integrating the concepts/product
of this efforts into a larger thing that I'm trying to do, so IMHO,
it's ok in this case if those two were defined global.

return EXIT_FAILURE; /* Only defined return codes from main are
0, EXIT_OK, and EXIT_FAILURE */


I think you mean EXIT_SUCCESS rather than EXIT_OK. It should also be
noted that returning 0 is defined as meaning success.


What's the big diff between EXIT_FAILURE and 1?! I mean, returning 1
just means generic error in the first place....

-Wes

Nov 15 '05 #15
ncf
Michael Mair wrote:
Hmm...how would I do the realloc later then if the space was never
alloc'd? Or would that be unnecessary as well? :slightly confused:
realloc(NULL, size) does the same thing as malloc(size),
realloc(ptr, 0) does the same thing as free(ptr).
Your implementation typically comes with a standard library
reference which you should look into; if not, try the C99
library reference on dinkumware.com

Hmm...interesting to know. Thank you for expanding and explaining. :) I
was always just working off of man pages (`man 3 malloc' and the like)
Hmm...I *think* I see what you're saying. By memory leak, I'm infering
that you mean memory that was never free()d for other applications to
use.


Yes and no. It may be also memory _you_ cannot use later on in
your program because you already allocated but sort of lost the
key to use it. If you need large amounts of memory this may be
the bit which makes your program exit earlier than planned due
to (self-inflicted) lack of memory...
As an aside, most modern operating systems clean up after an
application finished, so many well-known applications accept
that there are memory leaks in their code that could not be
tracked down. This is bad practice and may hide other errors
which then come down as soon as some minor detail changes. Just
avoid them :-)

Hehe, thanks for expanding :)

Hmm...I'm not too sure right now how it'd hide errors, but hey! It'll
make sense probably later on, so lets not worry too much about that.
I'll just take your word for it ;)


For one, it is not necessary. The other thing is that casts
are pretty strong: They tell the compiler to shut up.
In combination with the "implicit int" rule, this may shadow
the fact that you forgot to #include <stdlib.h> which in turn
can lead to odd effects if sizeof(int) is different from the
size of the respective pointer type you cast to -- it may go
well 99% of the time but every now and then, you have your
program eating your hard disc's contents or similar...

Ooh, prog eating my HD eh? Sounds like something I've done before in
Bash (accidently recursively deleted /usr/bin) :roll:

My, you _really_ have promise ;-)

Not really sure what you mean by "you _really_ have promise", but uhh,
ok :P (bad grammar constructs seem to make me get all confused easily)
Have a GREAT one :)

Nov 15 '05 #16

"ncf" <no***************@gmail.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...
Flash Gordon wrote:
However, if the variables were moved in to main (which would be
better style since using globals where they are not needed is bad style
and a very bad habit, then it would need initialising.
The code I'm working with right now has messages and num_messages in
the file scope because I'm going to be integrating the concepts/product
of this efforts into a larger thing that I'm trying to do, so IMHO,
it's ok in this case if those two were defined global.

> return EXIT_FAILURE; /* Only defined return codes from main are
> 0, EXIT_OK, and EXIT_FAILURE */


I think you mean EXIT_SUCCESS rather than EXIT_OK. It should also be
noted that returning 0 is defined as meaning success.


What's the big diff between EXIT_FAILURE and 1?!


EXIT_FAILURE is portable, 1 is not.
Standard C defines exactly three values for the return
value of main:

EXIT_SUCCESS
EXIT_FAILURE
zero (0) (or any integer expression which evaluates to zero)

0 also means 'success', but note that its actual value
need not be zero (but it often is).
I mean, returning 1
just means generic error in the first place....


Not in standard C it doesn't. The language doesn't give
it any meaning at all as the return value from 'main()'
(although some implementations might as an 'extension').

-Mike

Nov 15 '05 #17
ncf
Mike Wahler wrote:
What's the big diff between EXIT_FAILURE and 1?!


EXIT_FAILURE is portable, 1 is not.
Standard C defines exactly three values for the return
value of main:

EXIT_SUCCESS
EXIT_FAILURE
zero (0) (or any integer expression which evaluates to zero)

0 also means 'success', but note that its actual value
need not be zero (but it often is).
I mean, returning 1
just means generic error in the first place....


Not in standard C it doesn't. The language doesn't give
it any meaning at all as the return value from 'main()'
(although some implementations might as an 'extension').

Interesting. Well, I'll definately try to keep that in mind as I
continue into learning. I've just always used 0 or 1 as it just seems
to be somewhat conventional (like for sh scripts and the like).

-Wes

Nov 15 '05 #18

"ncf" <no***************@gmail.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
Mike Wahler wrote:
> What's the big diff between EXIT_FAILURE and 1?!


EXIT_FAILURE is portable, 1 is not.
Standard C defines exactly three values for the return
value of main:

EXIT_SUCCESS
EXIT_FAILURE
zero (0) (or any integer expression which evaluates to zero)

0 also means 'success', but note that its actual value
need not be zero (but it often is).


What I meant to say here is that although both
zero and 'EXIT_SUCCESS' designate 'successful
completion', the value of 'EXIT_SUCCESS' may
or may not be zero.

(Also note that even if main() returns zero, that
need not be the value received by the calling
environment. The implementation might translate
it to something more meaningful to that environment).

-Mike
Nov 15 '05 #19
ncf
Interesting concept. Well, thanks so much for the pointer on that. :)
-Wes

Nov 15 '05 #20
ncf wrote:
Michael Mair wrote:
My, you _really_ have promise ;-)


Not really sure what you mean by "you _really_ have promise", but uhh,
ok :P (bad grammar constructs seem to make me get all confused easily)


You not only took the advice and followed it but also
thanked the one giving it...

-Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 15 '05 #21
Michael Mair wrote:
ncf wrote:
Michael Mair wrote:
My, you _really_ have promise ;-)

s/have/show/

Not really sure what you mean by "you _really_ have promise", but uhh,
ok :P (bad grammar constructs seem to make me get all confused easily)


You not only took the advice and followed it but also
thanked the one giving it...

-Michael

--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 15 '05 #22
ncf wrote:
Flash Gordon wrote:
However, if the variables were moved in to main (which would be
better style since using globals where they are not needed is bad style
and a very bad habit, then it would need initialising.


The code I'm working with right now has messages and num_messages in
the file scope because I'm going to be integrating the concepts/product
of this efforts into a larger thing that I'm trying to do, so IMHO,
it's ok in this case if those two were defined global.


IMHO if it will be integrated in to a larger project that is an even
bigger reason to *avoid* using globals. I'll repeat that in general
globals are a bad idea. To provide a couple of reasons:
They provide non-obvious coupling between functions
The prevent you from reusing the function on a different piece of data

I'm not saying they should *never* be used, but something like a count
of messages does not sound to me like an appropriate use. After all, one
day you might want to have two sets of messages each with it;s own
num_messages.
return EXIT_FAILURE; /* Only defined return codes from main are
0, EXIT_OK, and EXIT_FAILURE */


I think you mean EXIT_SUCCESS rather than EXIT_OK. It should also be
noted that returning 0 is defined as meaning success.


What's the big diff between EXIT_FAILURE and 1?! I mean, returning 1
just means generic error in the first place....


No, under VMS 1 means success. The *only* portable values are those
quoted above, 0, EXIT_SUCCESS and EXIT_FAILURE. So if your program is
going to produce only one failure code you should use EXIT_FAILURE.

There are valid reasons for using non-portable return values (for
example when you need to flag different kinds of failure), but in that
case you should not use magic numbers but either enums of #defines so
that they can easily be changed when porting to other systems.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #23
"Mike Wahler" <mk******@mkwahler.net> writes:
"ncf" <no***************@gmail.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
Mike Wahler wrote:
> What's the big diff between EXIT_FAILURE and 1?!

EXIT_FAILURE is portable, 1 is not.
Standard C defines exactly three values for the return
value of main:

EXIT_SUCCESS
EXIT_FAILURE
zero (0) (or any integer expression which evaluates to zero)

0 also means 'success', but note that its actual value
need not be zero (but it often is).


What I meant to say here is that although both
zero and 'EXIT_SUCCESS' designate 'successful
completion', the value of 'EXIT_SUCCESS' may
or may not be zero.

(Also note that even if main() returns zero, that
need not be the value received by the calling
environment. The implementation might translate
it to something more meaningful to that environment).


And just to make it clear that this is more than just theoretical, VMS
(now called OpenVMS) defines any odd number as a successful status,
and any even number as a failure indication. The C implementation
translates exit(0) to return a status of 1, but it doesn't translate
any other values. So a program that does exit(0), exit(EXIT_SUCCESS),
or exit(EXIT_FAILURE) will behave as expected, but exit(1) will
indicate that the program succeeded. (I think EXIT_FAILURE may be
defined as 2, but I wouldn't bet on it.)

The fact that EXIT_SUCCESS isn't necessarily 0 may be just
theoretical, though; I've never heard of an implementation with
EXIT_SUCCESS != 0.

In some ways, it might have been clearer for the C standard only to
define the behavior of EXIT_SUCCESS and EXIT_FAILURE, leaving 0
implementation-defined.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #24
ncf wrote:
Flash Gordon wrote:

0, EXIT_OK, and EXIT_FAILURE */

I think you mean EXIT_SUCCESS rather than EXIT_OK. It should also be
noted that returning 0 is defined as meaning success.

What's the big diff between EXIT_FAILURE and 1?! I mean, returning 1
just means generic error in the first place....


EXIT_FAILURE has a standardly defined meaning as an argument to exit(),
as do 0 and EXIT_SUCCESS. On the other hand, 1 as an argument to exit()
does not have a standardly defined meaning, and it damn sure doesn't
mean "generic error in the first place."
Nov 15 '05 #25
ncf
> >>> My, you _really_ have promise ;-)
s/have/show/

Not really sure what you mean by "you _really_ have promise", but uhh,
ok :P (bad grammar constructs seem to make me get all confused easily)


You not only took the advice and followed it but also
thanked the one giving it...


Heh, thankee. I'd much rather say thank you than to not say it and
leave my appreciation unknown. :)

Have a GREAT day :)
-Wes

Nov 15 '05 #26
Martin Ambuhl wrote:
ncf wrote:
Flash Gordon wrote:


0, EXIT_OK, and EXIT_FAILURE */

I think you mean EXIT_SUCCESS rather than EXIT_OK. It should also be
noted that returning 0 is defined as meaning success.


What's the big diff between EXIT_FAILURE and 1?! I mean, returning 1
just means generic error in the first place....

EXIT_FAILURE has a standardly defined meaning as an argument to exit(),
as do 0 and EXIT_SUCCESS. On the other hand, 1 as an argument to exit()
does not have a standardly defined meaning, and it damn sure doesn't
mean "generic error in the first place."


Has it been noted recently that an arbitrary C program is often a
function called by the Unix shell in a program of its own?

By convention the shell, if it cares, will check the return value of the
function. Again, by convention, integer 0 indicates success and other
values indicate other things.

In any case, the return value of a C program is defined in the contract
between the C program and the shell program that called it. In other
words Implementation Specific.

Unhappily, the C Standard divorces itself from the Unix shell and does
not elaborate on the possible return values of a C programm beyond
EXIT_SUCCESS, 0 and EXIT_FAILURE.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 15 '05 #27
Flash Gordon <sp**@flash-gordon.me.uk> writes:
Niklas Norrthon wrote:
"ncf" <no***************@gmail.com> writes:

return EXIT_FAILURE; /* Only defined return codes from main are
0, EXIT_OK, and EXIT_FAILURE */


I think you mean EXIT_SUCCESS rather than EXIT_OK. It should also be
noted that returning 0 is defined as meaning success.


You are right of course. Personally I am usually too lazy to type it out,
so I use the zero for indicating success. Perhaps thats why my mind slipped.

Furthermore I'd say it's perfectly acceptable to use other return than
these, when coding for a specific platform where such return codes
make sense, and can carry additional information to the calling program,
(as long as one does not post such code in this forum)

/Niklas Norrthon

Nov 15 '05 #28

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

Similar topics

14
by: Joseph | last post by:
I am trying to create a function that allocates memory for the matrix through a function; like the code below. However, this does not seem to work since I believe that the scope of the memory...
8
by: Pegboy | last post by:
I am having trouble with malloc() again for a PC app I am developing. The method of the suspicious line of code seems to be Ok on a embedded platform, but not with the PC platform. The embedded...
11
by: Gustavo G. Rondina | last post by:
Hi all I'm writting a simple code to solve an ACM problem (http://acm.uva.es, it is the problem #468). In its code I have the following fragment: freq = calcfreq(hashfreq, strfreq, input);...
35
by: ytrama | last post by:
Hi, I have read in one of old posting that don't cast of pointer which is returned by the malloc. I would like to know the reason. Thanks in advance, YTR
11
by: lohith.matad | last post by:
Hi all, Though the purpose of both malloc() and calloc() is the same, and as we also know that calloc() initializes the alloacted locations to 'zero', and also that malloc() is used for bytes...
15
by: Martin Jørgensen | last post by:
Hi, I have a (bigger) program with about 15-30 malloc's in it (too big to post it here)... The last thing I tried today was to add yet another malloc **two_dimensional_data. But I found out that...
68
by: James Dow Allen | last post by:
The gcc compiler treats malloc() specially! I have no particular question, but it might be fun to hear from anyone who knows about gcc's special behavior. Some may find this post interesting;...
25
by: Why Tea | last post by:
Thanks to those who have answered my original question. I thought I understood the answer and set out to write some code to prove my understanding. The code was written without any error checking....
71
by: desktop | last post by:
I have read in Bjarne Stroustrup that using malloc and free should be avoided in C++ because they deal with uninitialized memory and one should instead use new and delete. But why is that a...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...

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.