From: "Hal E. Fulton" Date: 2001-06-09T16:11:30+09:00 Subject: [ruby-talk:16348] Re: Little bug in the manual ----- Original Message ----- From: Mathieu Bouchard To: ruby-talk ML ; teespy Cc: ruby-talk ML Sent: Thursday, June 07, 2001 7:30 PM Subject: [ruby-talk:16313] Re: Little bug in the manual > > I think there is a little error in ruby's guide > > ( www.ruby-lang.org/en/pdf-doc/rubyguide_A4.pdf ) > > Look at page 16, the C example of a loop, quoting: > > char *str; > > for (str = "abcdefg"; *str != '\0'; str++) { > > /* process a character here */ > > } > > I think 'str = "abcdefg"' isn't legal, and should be replaced with > > strcpy(str, 'abcdefg'); > > That's it, nothing important, but may be worth fixing in the next release of > > the guide. > > Not only str="abcdefg" is legal and working, but your replacement has > several errors in it. > > Please learn the difference between a character literal and a string > literal; and then learn about initializing all your variables; then learn > about the use of memory allocation and deallocation; then learn how you > can fix your code; then learn why the original code can be right too. > > That's it, nothing important, but may be worth learning for your next > post about C code. Let us give him a little assistance here. When you declare a pointer in C, you get only a pointer. There is no memory allocated for the thing pointed to. (It is truly frustrating how many people don't seem to know this -- it seems like a C newbie issue, but I have been frightened by "oldbies" (?) who didn't grasp it...) char *str; strcpy(str,"hello"); /* Coding error! Probable crash, now or later. */ This is better: char *str; str = (char *) malloc(10); strcpy(str,"hello"); /* No problem. */ Of course, the use of malloc() implies the later use of free(), or you will have a memory leak. A string constant is stored internally as a pointer to a character string. So it is legal to assign the pointer value to a pointer variable. No malloc() is required, since the memory already exists. char *str; str = "hello"; /* Memory for constant allocated at compile time. */ Does that help some? Cheers, Hal