Mailing List Archive

Support open source code!


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: tlug: gcc question



I would say this question is more appropriate on a c mailing
list or news group but I will try to answer it anyway:

Your code is broken in a way that will show up differently on
different OSes.

"Drew C. Poulin" wrote:
> 
> #include<stdio.h>
> 
> main(){
> 
>   char *fname, *lname;
Defines two pointers to char arrays. Usually the pointers are
initialized to 0x0000, but you can never be sure.... 
> 
>   puts("Enter fname:\n");
Prints a message
>   gets(fname);
Reads user input and writes it to wherever the fname pointer 
points (probably to 0x000, which will give you an exception
in Linux but not in all OSes (but it is a bug in all OSes)).
>   puts("Enter lname:\n");
>   gets(lname);
Se above.
>  printf("First name: %s\tLast name: %s\n", fname, lname);
> 
> }
For short, your pointers are not properly initialized.
Easiest fix would be to define fname and lname
to be
   char fname[1024] ;
   char lname[1024] ;
Note that fname/lname are still pointers, but initialized 
to point to char[1024] arrays, that is 1024 long
character strings. This way you can enter up to 1023
characters into fname/lname without an error (the last
character is required for the terminating zero).

This pointer/array stuff is one of the things in c that 
beginners find complicated. Most other languages
don't bother about pointers and stuff but in c they are
vital. 

It is also important to remember that there is no
built in bounds checking in c arrays. None. At all.
C is difficult for a beginner since it is essentially
a more or less portable assembler on steroids.

But it is also very common, portable and the language
of choice for most people in the Linux community (makes
you wonder... ;-)

have fun...

/Fredric
-------------------------------------------------------------------
Next Technical Meeting: January 14 (Fri) 19:00
* Topic: "glibc - current status and future developments"
* Guest Speaker: Ulrich Drepper (Cygnus Solutions)
* Place: Oracle Japan HQ 12F Seminar Room (New Otani Garden Court)
-------------------------------------------------------------------
more info: http://www.tlug.gr.jp        Sponsor: Global Online Japan


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links