1

I'm writing a similar program on C on Ubuntu. The task is to show the output on console. I am using gcc compiler. The task is to get such an output 12, Name Surname, 36, my lapt, -11, but instead i get 12, apt, 36, my lapt, -11. I know that my program is overwriting a at strncat(d, c, 4);, but i don't know the reason why.

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

int main()
{
char a[] = "Name";
char b[] = "Surname";
strcat(a, b);
int x = strlen(a);
int y = strcmp(b, a);
char d[] = "my ";
char c[] = "laptop";
strncat(d, c, 4);
int z = strncmp(a, c, 2);
printf("%d, %s, %d, %s, %d\n", x, a, y, d, z);
return 0;
}
2
  • 3
    a only has space to store 5 bytes, including string terminator. You can't strcat anything into it - you'll get undefined behavior. Commented Nov 27, 2020 at 12:37
  • 1
    d is not big enough Commented Nov 27, 2020 at 12:38

1 Answer 1

2
char a[] = "Name";
char b[] = "Surname";
strcat(a, b);

is wrong. a does not have room. It's size is only 5. This would work:

char a[20] = "Name"; // 20 is arbitrary, but it's big enough for the strcat
char b[] = "Surname";
strcat(a, b);

Same goes for the d array

This can be read in documentation

char * strcat ( char * destination, const char * source );

[The parameter destination is a] Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string.

Always read the documentation for functions you're using.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.