If you are using the function strncpy
then you have to set its last character to the zero character '\0'. Otherwise you can not guarantee that the character array contains a string.
Using strncat
this way
strncat(filename, attr, sizeof(filename));
does not make sense. The array filename
can have no enough space to accommodate the string attr
. But you are trying to copy sizeof(filename)
characters to an array that already can be entirely filled.
You have to check "manually" whether the destination array contains enough space to append a new string to the already stored string.
So there is no sense to use the function strncat
because in any case the result path will be invalid.
You can use the following approach shown in the demonstrative program below.
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 512
void some_function(const char *path )
{
char filename[MAX_SIZE] = "";
const char *attr = "/funct";
size_t n = strlen( attr );
strncpy( filename, path, sizeof (filename ) );
filename[ MAX_SIZE - 1] = '\0';
if ( n < MAX_SIZE - strlen( filename ) )
{
strcat( filename, attr );
}
puts( filename );
}
int main(void)
{
const char *path = "/path";
some_function( path );
return 0;
}
Or you could at the very beginning of the function check whether the array can contain the both strings. For example
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 512
void some_function(const char *path )
{
char filename[MAX_SIZE] = "";
const char *attr = "/funct";
size_t n1 = strlen( path );
size_t n2 = strlen( attr );
if ( n1 + n2 < MAX_SIZE )
{
strcpy( filename, path );
strcpy( filename + n1, attr );
}
puts( filename );
}
int main(void)
{
const char *path = "/path";
some_function( path );
return 0;
}