On May 23, 10:42 pm, Bob Harris <nospam.News....@remove.Smith-
Harris.us> wrote:
> In article
> <7f6b9844-a1b5-42f1-aadb-6cc116726...@m3g2000hsc.googlegroups.com>
[quoted text clipped - 55 lines]
>
> Bob Harris
Okay, Do me a favor: Paste the following code into foo.c and compile
using:
gcc -ansi - pedantic -Wall -O2 -o test foo.c
#define SUCCESS 1
int main(int argc, char* argv[]){
char *p;
p = fgets(p, 50, stdin);
printf("%s\n", p);
return SUCCESS;
}
Then run test. It should require you to type a line and upon pressing
return,
should echo the line.
I am compiling using
gcc version 4.0.1 thread model: posix Max OS X Power PC architecture.
Tell me the compiler version you use, and any errors you get, if any.
Reinder Verlinde - 24 May 2008 11:31 GMT
In article
<362956e7-319a-41b2-9074-130875daa6cb@a70g2000hsh.googlegroups.com>,
> Okay, Do me a favor: Paste the following code into foo.c and compile
> using:
[quoted text clipped - 17 lines]
>
> Tell me the compiler version you use, and any errors you get, if any.
The first error I get is one in my head that shouts "p is not
initialized".
I haven't tried compiling this, but I would guess that, according to the
C standard, this program has 'undefined behavior'.
Try to declare p as
char * p = malloc(51);
....
free(p)
or
char p[51];
instead.
Reinder
Bob Harris - 24 May 2008 15:18 GMT
In article
<362956e7-319a-41b2-9074-130875daa6cb@a70g2000hsh.googlegroups.com
>,
> On May 23, 10:42 pm, Bob Harris <nospam.News....@remove.Smith-
> Harris.us> wrote:
[quoted text clipped - 74 lines]
> return,
> should echo the line.
I do not need to compile this. It is broken code.
'p' is suppose to have some storage behind it. In the code you
provide, 'p' contains random data. You are passing an address to
fgets(p,...) which is random. fgets() is storing your input
somewhere random in memory.
It is my guess that on Linux the random address is someplace
inside of your program that is not immediately harmful. On Mac OS
X, it is most likely an address that is outside the bounds of your
program so you are getting a SIGBUS error.
As others have suggested, you need to give 'p' some storage
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char* argv[])
{
char p[50];
if ( fgets(p, sizeof(p), stdin) == NULL ) {
perror("fgets()");
exit(EXIT_FAILURE);
}
printf("%s\n", p);
return(EXIT_SUCCESS);
}
This will work, and is better coding style, since the size of 'p'
is used as the maximum length to fgets().
EXIT_SUCCESS and EXIT_FAILURE are standard exit codes provided by
stdlib.h
Bob Harris
30+ years writing code
20+ years in C alone
> I am compiling using
> gcc version 4.0.1 thread model: posix Max OS X Power PC architecture.
>
> Tell me the compiler version you use, and any errors you get, if any.