[Solved] Does under-utilized memory cause memory leak?


In fact these two statements

char buffer[32];
strncpy(buffer,uk,sizeof(buffer));

are fully equivalent to the following declaration

char buffer[32] = "ln";

It is a valid declaration and there is no bug or memory leak.:)

In the both cases all elements of buffer that were not initialized by the string literal’s characters (or by copying of its characters) are zero initialized.

From the C Standard (7.23.2.4 The strncpy function)

3 If the array pointed to by s2 is a string that is shorter than n
characters, null characters are appended to the copy in the array
pointed to by s1, until n characters in all have been written.

In general it would be more correctly to write

char buffer[32];

strncpy(buffer,uk,sizeof(buffer));
buffer[sizeof( buffer )-1] = '\0';

That is your original code is unsafe.

Of course header <string.h> in C or <cstring> in C++ has to be included but I think you simply forgot to do this for the demonstrative example.:).

2

solved Does under-utilized memory cause memory leak?