Will StrDUp () create
\ 0 '
at the end of the dynamic array?
char buf [128];
BUF [0] = 'X';
for (int i = 1; i & lt; 64; i ++)
{
buf [i] = i;
}
char * str = STRDUP (BUF);
Answer 1, Authority 100%
Firstly, you have a typo in the last line:
char * str = StrDUp (DUF); // Need Buf.
And secondly, it is enough to make man 3 Strdup to read:
description
The StrDUp () function returns a pointer to a new string that is a duplicate string s.
Memory under the new line will be allocated using Malloc (3) and can be released using
FREE (3).
The strndup () function is similar to the previous one, but copies no more than N byte. If S is longer than n, then
Only N byte is copied and the finite byte NULL ('\ 0') is added.
From here we draw conclusions:
- times we are talking about row (in understanding C), then the character ‘\ 0’ is obliged to be to be present in the source row. (Error in your program)
- If the string is too long, then strndup will automatically insert this symbol where need.
Answer 2, Authority 25%
when i = 0
; buf [i] = i;
Strdup
will create an empty string. Zero is a sign of the end of the line and always copied, as stated in the documentation. The argument of the function is the pointer, and the function is not “knowing” the size of the array. Strndup
will make the same, it cuts the string and adds a zero symbol only if it does not meet it to the n-th element.
And where does such a curve implementation of Strdup in response? It is usually implemented here so
char * stradup (const char * s)
{
Size_t Len = strlen (S) + 1; // Line length including zero symbol
char * result = (char *) malloc (len);
if (result == (char *) 0) // or if (! result)
Return (char *) 0;
// We already know the length of the string and want to use RVO
Return (Char *) Memcpy (Result, S, Len);
}
either using embedded functions. StrCpy – time loss when the length of the line is known.
Call strlen (s), if since the address s is there is no zero symbol within the specified array, it is a source of uncertain behavior.strdup and strlen are sources of potential security holes precisely because of this, StrDUp is more important. It is allowed to “leak” somewhere as a result of copying.
Answer 3
No! Strdup
Function is designed to work with rows therefore it can not add the end symbol to the end character, but if the array already has '\ 0'
the function will copy it.
char buf [128];
BUF [0] = 'X';
for (int i = 1; i & lt; 64; i ++)
{
buf [i] = i;
}
BUF [64] = '\ 0'; // ← ← Something like that
char * str = STRDUP (BUF);
In fact, the Strdup
function is equivalent to the following code:
char * stradup (const char * s)
{
char * d = malloc (strlen (s) + 1); // Space for Length Plus Nul
if (d == null) Return NULL; // No Memory.
STRCPY (D, S); // Copy The Characters
RETURN D; // Return The New String
}