haccks haccks - 5 months ago 23
C Question

Is it undefined behavior if the destination string in strcat function is not null terminated?

The following program

// Code has taken from http://ideone.com/AXClWb
#include <stdio.h>
#include <string.h>

#define SIZE1 5
#define SIZE2 10
#define SIZE3 15

int main(void){
char a[SIZE1] = "Hello";
char b[SIZE2] = " World";
char res[SIZE3] = {0};

for (int i=0 ; i<SIZE1 ; i++){
res[i] = a[i];

strcat(res, b);
printf("The new string is: %s\n",res);
return 0;

has well defined behavior. As per the requirement, source string
is null terminated. But what would be the behavior if the line

char res[SIZE3] = {0}; // Destination string

is replaced with

char res[SIZE3];

Does standard says explicitly about the destination string to be null terminated too?


TL;DR Yes.

Since this is a language-lawyer question, let me add my two cents to it.

Quoting C11, chapter § (emphas is mine)

char *strcat(char * restrict s1,const char * restrict s2);

The strcat function appends a copy of the string pointed to by s2 (including the terminating null character) to the end of the string pointed to by s1. The initial character of s2 overwrites the null character at the end of s1.[...]

and, by definition, a string is null-terminated, quoting §7.1.1/1

A string is a contiguous sequence of characters terminated by and including the first null character.

So, if the source char array is not null-terminated (i.e., not a string), strcat() may very well go beyond the bounds in search of the end which invokes undefined behavior.

As per your question, char res[SIZE3]; being an automatic local variable, will contain indeterminate value, and if used as the destination of strcat(), will invoke UB.