You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用memcmp比较字符串字面量时越界访问是否属于未定义行为?

Is accessing out-of-bounds memory with memcmp a case of undefined behavior?

I used the memcmp function 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, str2 is shorter than str1, and accessing str2 will cause an out-of-bounds situation. Is this undefined behavior?

Absolutely, this is undefined behavior. Let’s break down the reasoning clearly:

  • First, str2 is initialized as char str2[] = "ab"; which creates a 3-byte array: it holds the characters 'a', 'b', plus the mandatory null terminator \0. When you pass 4 as the third argument to memcmp, you’re instructing the function to read 4 consecutive bytes starting from the address of str2.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:13:08