使用memcmp比较字符串字面量时越界访问是否属于未定义行为?
Is accessing out-of-bounds memory with memcmp a case of undefined behavior?
I used the
memcmpfunction to compare two string literals, here's my code:#include <stdio.h> #include <string.h> int main() { char str1[] = "abcd"; char str2[] = "ab"; if (memcmp(str1, str2, 4) == 0) { printf("equal string\n"); } return 0; }In the above program,
str2is shorter thanstr1, and accessingstr2will cause an out-of-bounds situation. Is this undefined behavior?
Absolutely, this is undefined behavior. Let’s break down the reasoning clearly:
- First,
str2is initialized aschar str2[] = "ab";which creates a 3-byte array: it holds the characters 'a', 'b', plus the mandatory null terminator\0. When you pass4as the third argument tomemcmp, you’re instructing the function to read 4 consecutive bytes starting from the address ofstr2. - The C standard explicitly states that accessing memory outside the bounds of a defined object is undefined behavior. There’s no guarantee what lives in that extra memory beyond
str2—it could be garbage data, other variables, or even memory that’s not mapped to your program at all. - Undefined behavior means the compiler has no obligation to handle this scenario predictably. Your code might seem to run fine in some cases, crash immediately in others, or even get optimized in weird ways (like the compiler stripping out the entire comparison block) because it assumes you won’t trigger invalid memory accesses.
To fix this, you should either compare only up to the length of the shorter string, or use strcmp instead if you’re working with null-terminated strings—strcmp automatically stops comparing once it hits a null terminator, avoiding out-of-bounds access entirely.
内容的提问来源于stack exchange,提问作者msc
相关产品推荐
相关产品推荐

