-3

I am trying to understand when I specify the value of "strx" more than 10 characters, it always leads to strcmp showing up the value of -1 whereas when I specify value of strx less than 10 characters then strcmp shows the correct value of 0.

My specific question: if we specify the value of strx more than the size of str1, why does the strcmp gives up the false result of -1?

PS: I tried to print the str1 and strx after the copy and it shows same output.

#include <stdio.h>
#include <string.h>
int main()
{
char strx[]="123456789101112";
char str1[10];
strcpy(str1,strx);
int ret;
ret = strcmp(str1,strx);
printf("%d\n", ret);
    if(ret == 0)
    {
        printf("Intact. Try Again\n");
        printf("Str1 = %s\n",str1);
    }
    else
    {
        printf("Overflow successful\n");
    }
return 0;
}
r0x0t
  • 19
  • 2

1 Answers1

0

The comment by Antti Haapala more or less sums it up. Undefined behavior is undefined. Once you invoke it, you lose the right to complain about anything else the program might do.

In particular, in you case, one of your assertions is wrong. You claimed that if you print the strings they are the same. At least for me, that's not the case:

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

int main()
{
    char strx[]="123456789101112";
    char str1[10];

    strcpy(str1,strx);
    printf("%s\n", strx);
    printf("%s\n", str1);
    int ret;
    ret = strcmp(str1,strx);
    printf("%d\n", ret);
    if(ret == 0)
    {
        printf("Intact. Try Again\n");
        printf("Str1 = %s\n",str1);
    }
    else
    {
        printf("Overflow successful\n");
    }
    return 0;
}

That prints:

01112
123456789101112
1
Overflow successful

Your assumption that strx is located before str1 in memory is incorrect. When you overflow str1 you change strx.

Shachar Shemesh
  • 8,193
  • 6
  • 25
  • 57