Vine
Geekoaur answered your question well, I just point out another โproblemโ with your code.
String s1[strlen(s1)] = '\0'; is no-op if s1 already completely zero termination before it is executed.
But if s1 NOT all true zero termination before this line is executed (and you're out of luck), this will result in:
- a SIGSEGV on a POSIX system (* nix).
- a GPF on Windows.
This is because strlen basicaly finds the index of an existing null terminator and returns it! Here's a valid, non-optimized strlen implementation:
int strlen(char *string) { int i = 0; while(string[i] != '\0') { ++i; } return i; }
So ... If you REALLY worry that the lines were NOT terminated by zeros, you would do something like:
string[sizeof(string)]='\0'; in local automatic strings (where the compiler โknowsโ the size of the string);- or
string[SIZE_OF_STRING] for all other strings, where SIZE_OF_STRING (usually) a #define 'd constant or variable that you support specifically to store the current SIZE (not length) dynamically allocated string.
And if you REALLY, REALLY, REALLY worried that the lines did not end in zero (for example, you deal with dirty methods libary (for example, Tuxedo ATMI), you ALSO clear "your" return lines "before passing them to methods suspicious library using:
- before:
memset(string, NULL, SIZE_OF_STRING); - invoke:
DirtyFunction(/*out*/string) ; - after:
string[SIZE_OF_STRING]='\0'
SIG11 is a complete search binding because (if you didnโt โhookโ them with the signal processor and didnโt say otherwise, they cause unix to hard-end your program, so you cannot register anything (after the fact) to help find out where-in-a-a-a-o-o-o-o-o-o ... especially considering that in many cases the line of code that throws SIG11 is not next to the actual reason that the line loses the zero delimiter .
Does that make sense to you?
Greeting. Whale.
PS: WARNING: strncpy IS NOT ALL IMPOSSIBLE ... you probably meant strlcpy . I learned this hard way ... when billing for $ 60 million worked.
EDIT:
FYI: Here is the "safe" (non-optimized) version of strlen, which I will call strnlen (I believe it should be in stdlib. Sigh.).
// retuns the length of the string (capped at size-1) int strnlen(char *string, int size) { int i = 0; while( i<size && string[i]!='\0' ) { ++i; } return i; }
corlettk
source share