Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a char array without the null terminator?

The char array is a part of network message, which has well defined length, so the null terminator is not needed.

struct Cmd {
    char cmd[4];
    int arg;
}

struct Cmd cmd { "ABCD" , 0 }; // this would be buffer overflow

How can I initialize this cmd member char array? without using functions like strncpy?

like image 579
fluter Avatar asked May 13 '19 04:05

fluter


1 Answers

Terminating null character is ignored if the size of the char array is the same as the number of characters in the initializer. So cmd will not have the null terminator.

The relevant section in the C11 standard (n1570) is 6.7.9/14:

An array of character type may be initialized by a character string literal or UTF−8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

And the statement:

struct Cmd cmd { "ABCD" , 0 };

should be:

struct Cmd cmd  = { "ABCD" , 0 };
like image 170
P.W Avatar answered Oct 17 '22 01:10

P.W