JC said:
On Jun 18, 11:28Â pm, Ben Bacarisse <
[email protected]> wrote:
Eek! Â Now either *node or (*node)->elem can be NULL and both
conditions cause trouble!
Ah, this is a stupid bug I made. thanks.
and also, strncpy should be called like:
strncpy ((*node)->elem, elem, strlen (elem));
(*node)->elem[strlen(elem)] = '\0';
I can't emphasise enough: strncpy should not be called at all! It
works fine as you first had it:
strncpy ((*node)->elem, elem, strlen (elem) + 1);
but it has to do more work than is needed (it must test for a null
that comes only when the counter runs out and it must test the counter
that runs out only at the null) and getting used to using it is a bug
waiting to happen.
I have been programming in C for nearly 30 years and I last used
strncpy about 29 years ago when it was exactly what was needed to copy
Unix file names into directory entries because these were not
null-terminated unless they were < 14 characters long (in which case
you had to pack the space with nulls). I think it was invented
because of this format, and I have never used it since (except in an
embarrassingly erroneous posting here a few years ago). It is almost
never the best function for the job: strcpy does what you want
and is simpler; memcpy does it better if you have the length already.
malloc can used like this to malloc for struct and string,
I never saw it.
This is a hack. Please be aware of that. For example, it works
because char has no alignment needs. If you ever switch to wide
characters this code will break.
My real point was this: allocate both or neither. You had a situation
where you allocate the node and then return an error because the
string could not be allocated. This is (depending on exactly how you
use the result) a memory leak.
The better design is only give CLinkedNode **node parameter to
C_Node_Alloc_and_Init
function?
I am not sure what you mean.
Here, I can remove oldp->elem == NULL; oldp->next = NULL;?
Yes.
because oldp is a local variable?
No, because you are going to call free:
Everything that oldp pointed at has now gone. Why set something that
is going to be thrown away?
remove oldp = NULL; here too?
Yes. At the end of the loop...
.... oldp vanishes. You get a new oldp at the start of the next loop
iteration (or you leave the loop and there is nothing called oldp
anymore). There is no point in setting a variable to anything just
before the end of its lifetime.
Excellent!!
Ben, you are really expert's expert!
<blush>