[Sussex] Re: C programming help

Geoffrey J. Teale tealeg at member.fsf.org
Wed May 11 06:43:43 UTC 2005


On Wed, 2005-05-11 at 06:27 +0100, Captain Redbeard wrote:
> Alright, but I'm a bit of a perfectionist and would prefer 
> my code to have no errors at all even if that's a near 
> impossibility.  Besides, memory allocation is one area I'm 
> still trying to get my head around so I don't always 
> necessarily know if what I think should work actually does 
> work (though I'm learning fast!).

Keep at it.  My only point was I'ts really rare to find a program that
Valgrind can't find at least some problems in.

> Hope so. :)
> 
> The main reason I'm writing the program in C is so that I 
> can really get inside the language and learn it well, even 
> though I've opted for an OOP-style approach that would 
> probably be better suited to Java or C++.  It's just a 
> little annoying sometimes how long it is taking to get what 
> is essentially quite a simple program stable enough to be 
> released.  On the other hand I have BIG plans for it so it's 
> probably best to get it right the first time.

C development can be very slow at first.  People tend to build up their
own libraries of code to help speed things along though.  Like anything,
it gets easier the more you do.

> Oh, and finally, IS there anything wrong with the line 
> "strncpy (TestStructPtr->CharString, "Hello World!\n\n\n", 
> 13);" and why am I getting that error message from Valgrind?

Two things.

1. As Steve points out you are only copying 13 chars from a 15 character
string.  This is OK, but you may need to add a NULL terminator (\0) on
the end if you want to carry on using standard functions on the
resulting string.  The string you copied had a NULL terminator already
(even though you can't see it), you just chopped it off.


2. strncpy returns a pointer to the resulting string - you're not
capturing this anywhere.  Again, this OK as it should match the address
of TestStructPtr->CharString  - in a paranoid world you could check that
the two match, or simply cast the call to (void *).

As a general rule I'd keep this manual bookmarked:

http://www.gnu.org/software/libc/manual/html_node/index.html

.. and read the relevant entries carefully.

-- 
Geoffrey J. Teale <tealeg at member.fsf.org>
Free Software Foundation





More information about the Sussex mailing list