0

I am very new to C.

Could you, please, point me out what part of my code (function, some of the operators, wrong strings declaration, etc) is making the following output in console:

enter image description here

I expect to have OmelianLevkovych.

The following code snippet:

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

const char* GetFullName(char firstName[], char lastName[])
{
    return strcat(firstName, lastName);
}

int main()
{

    char firstName[] = "Omelian";
    char lastName[] = "Levkovych";

    char* fullName;

    fullName = GetFullName(firstName, lastName);

    printf("%s", fullName);
    return 0;
}

I am using Code.Block IDE 20.03 (default hello-world template proj).

  • 2
    `char firstName[] = "Omelian";` that will make an array that fits exactly that string. Trying to write more to it, like you do with `strcat`, results in Undefined Behaviour. One fix is to declare a larger array: `char firstName[128] = "Omelian";` – kaylum Sep 14 '21 at 20:39
  • @kaylum, sorry, do you mean that my GetFullName func returns actually the same first string, right? So the `strcat()` do not create another string literal but actually returns the first string as result (obviously also adding another string(s) to it)? – Omelian Levkovych Sep 14 '21 at 20:45
  • 1
    funny, i just put this code in onlinegdb.com and it works. although it should not :D – Effie Sep 14 '21 at 20:45
  • @effenok It can work sometimes. Depends on whats directly behind the firstname string in memory. – The Average Google User Sep 14 '21 at 20:48
  • 1
    "undefined behavior" means just that. Sometimes it "works", sometimes it doesn't. The behavior can change from one run to the next, from system to system, with different compiler flags, etc. As soon as you invoke UB (in this case, overwriting the bounds of an array), all bets are off in terms of how the program will continue to execute from then on. – yano Sep 14 '21 at 20:54
  • i want to add comment to the answer. In most high-level languages you can write something like str0 = str1 + str2; what actually happens is: first a new string is created with enough space to hold both str1 and str2. Then str1 and str2 are copied into a new string. In c you need to write this yourself. strcat only provides you with the second part. – Effie Sep 14 '21 at 21:33
  • @effenok yea, that was actually the reason why I have mislead the way how strcat works :) I was expecting it to work something like + operator in high-level languages. Thanks – Omelian Levkovych Sep 14 '21 at 21:40

1 Answers1

2

You dont have enough space allocated in the string firstname. Strcat appends lastname to firstname string and returns a pointer to firstname string.

The quick fix would be :

char firstName[30] = "Omelian";