user4918296
user4918296

Reputation:

strncat(): Random character in target string

Consider the following program:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {

    int ret = 0;

    char dirname[] = "test/";
    int path_maxlen = 256;
    char path[path_maxlen];
    int filename_maxlen = path_maxlen - strlen(dirname);

    strncat(path, dirname, path_maxlen - 1);

    strncat(path, "file.txt", filename_maxlen);

    FILE *file = fopen(path, "r");

    printf("path: %s\n", path);

    if (file != NULL) {
        printf("success\n");

        fclose(file);
    } else {
        printf("fail\n");
        ret = 1;
    }

    return ret;
}

This seemed to work at first but then it started to fail, i.e., the file could not be opened although it was present and no changes were made to the program or the file.

At that point I added the line that prints out path. After redirecting output to a file it turned out that path was preceded by a random character (ASCII: 1 SOH 'start of heading'). So I assume that strncat is not properly used here and some random junk gets written to my path array.

How do I correctly concatenate the strings in the above example?

PS: My OS is Ubuntu 16.04. The compiler is:

$ gcc --version
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609

Upvotes: 1

Views: 289

Answers (1)

AlexD
AlexD

Reputation: 32576

strncat(path, dirname, path_maxlen - 1);

path is uninitialized, so it is undefined behavior.

Try

char path[path_maxlen];
path[0] = 0; // since path is VLA, usual "={0}" initialization does not work 

Or you can consider using just strcpy_s.

Upvotes: 4

Related Questions