Anastasiya Toronenko
Anastasiya Toronenko

Reputation: 21

Invalid output in C program on Linux

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;
}

Upvotes: 1

Views: 139

Answers (1)

klutt
klutt

Reputation: 31296

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.

Upvotes: 2

Related Questions