[Sussex] Re: C programming help
Steve Dobson
steve at dobson.org
Wed May 11 06:26:17 UTC 2005
Redbeard
On Wed, May 11, 2005 at 06:27:44AM +0100, Captain Redbeard wrote:
> 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?
In and off itself in isolation, no. But you must always look
at the rest of the code.
By my count the string has 15 characters so you need at least
16 bytes to store that string. By only coping 13 characters
the nul terminator (every string is terminated will a nul
character) is not copied and so the string pointed by
TestStructPtr->CharString is not terminated. Your code has
to handle this, for example:
TestStructPtr->CharLen = 13;
TestStructPtr->CharString =
(char *) malloc(TestStructPtr->CharLen + 1);
.
.
.
const char *str = "Hello World!\n\n\n";
bzero(TestStructPtr->CharString,
TestStructPtr->CharLen + 1);
strncpy (TestStructPtr->CharString, str,
TestStructPtr->CharLen);
Hope this helps.
Steve
More information about the Sussex
mailing list