In said:
char composefile(void)
{
char KK[]="hola";
return (&KK);
}
Your array KK cease to exist once composefile() returns, so the pointer
you return isn't valid.
#define BUFFER_LENGTH 5
#include <stdio.h>
#include <string.h>
void composefile(char *);
int main(void) {
char buffer[BUFFER_LENGTH];
composefile(buffer);
printf("%s",buffer);
}
void composefile(char *b) {
char KK[] = "hola";
strncpy(b,KK,BUFFER_LENGTH);
}
You don't want to use strncpy here. If "hola" gets replaced by "hello",
composefile() no longer "returns" a string to its caller. strncat is
what you want:
*b = 0, strncat(b, KK, BUFFER_LENGTH - 1);
The code may still not behave as expected, but there is no undefined
behaviour when the caller attempts to use the string: the original string
merely gets truncated.
Of course, the same effect can be achieved with strncpy itself:
strncpy(b, KK, BUFFER_LENGTH), b[BUFFER_LENGTH - 1] = 0;
but it looks kinda silly and the assignment is redundant any time less
than BUFFER_LENGTH characters have been copied. For very large values
of BUFFER_LENGTH, there may be also a performance problem if the number
of copied characters is much less than BUFFER_LENGTH, because strncpy also
performs null padding, *always* writing BUFFER_LENGTH characters to the
destination (for purely historical reasons).
Despite its misleading prefix, strncpy is not to be used in a string
context. It was designed to manipulate a different data type, best called
"limited length string", where a terminating null character is not needed
if the string has the maximum allowed length. Of course, this maximum
length must be known to both caller and callee in the above example,
which could be rewritten like this:
int main(void)
{
char buffer[BUFFER_LENGTH];
composefile(buffer);
printf("%.*s\n", BUFFER_LENGTH, buffer);
return 0;
}
void composefile(char *b)
{
char KK[] = "hola";
strncpy(b, KK, BUFFER_LENGTH);
}
The only (relevant) difference from the original example is that
main() no longer relies on buffer to contain a C string after calling
composefile(): printf() is explicitly instructed not to display more
than BUFFER_LENGTH characters from buffer.
Dan