简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM