Reputation: 15
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
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:
Upvotes: 2
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