user2967800
user2967800

Reputation: 15

Why this code is not returning 0?

Why is this code returning -1?

memcmp() compares block of memory and takes 3 parameters in constructor but what happens when I miss the third parameter?

int main()
{
    char ptr[] = "hello";
    char ptr1[] = "hello";

    int a = memcmp(ptr,ptr1);
    printf("%d",a);

    return 0;
}

Also the following program abruptly terminates without the third parameter:

int main()
{
    char *ptr = "hello";
    char *ptr1 = "hello";

    int a = memcmp(ptr,ptr1);
    printf("%d",a);

    return 0; 
}

Upvotes: 0

Views: 185

Answers (2)

haccks
haccks

Reputation: 106032

It will compile neither in C nor in C++. In C, first one does compile only when you do not include <stdlib.h> and it simply invokes undefined behavior because passing arguments to a function less than that of its parameter invokes UB.

Here is the output:

enter image description here

Upvotes: 2

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

For starters, memcmp() takes three arguments: the pointers to the memory segments to be compared and the size. Although the code may compile in C (I don't think it should) it certainly doesn't compile using C++. If the code compiled, the third argument is a pretty random value and it is unlikely that the memory after these strings is the same.

Upvotes: 4

Related Questions