I think reading memory should not cause any issue eg

char *d="";
char *d2="test";
memcmp(d,d2,10);

Can memcmp() ever fail ?

有帮助吗?

解决方案

Your assumption is incorrect, as reading memory at an address not mapped into the process's address space will cause a SEGV. Particularly reading address 0 (on almost all architectures), and reading kernel memory space (if it's even mapped in), but in general reading logical memory to which no physical memory is mapped as readable.

In your example you are running memcmp on bytes that are not allocated, which is undefined behaviour. It will probably read garbage from the stack or data segment, but you have no way of knowing that. For instance, d might be right at the top of the stack and you might thus run beyond the top of the stack into unmapped memory (the stack generally grows downwards).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top