Re: Pointer within structure question
On Tue, 12 May 2009 05:48:07 -0700 (PDT), mzdude <jsanga@cox.net> wrote:
if you are really doing this in C (as opposed to C++) then
dynamic allocation and releasing the memory is much more
involved.
// Warning. Untested
int main(int argc, char* argv[])
{
struct B bk;
bk.asample = malloc(sizeof(A));
bk.asample->a = malloc(256); // a fairly long string
strncpy(bk.asample->a, "Hello world", 256);
You know you allocated enough memory, so just use strcpy. Using strncpy as
above is slower and zero-fills the remainder of the array. More generally,
using strncpy as above leads to buffer overruns when used with printf as
below. To see why, consider that strncpy does not nul-terminate the
destination string when the source string is longer than the max-chars
argument. If you just can't trust yourself, use the "safe string" functions
MS introduced a few years ago.
printf("%s\n",bk.asample->a);
free(bk.asample->a);
free(bk.asample);
return 0;
}
--
Doug Harrison
Visual C++ MVP