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

C++代码中str函数返回值始终为null的问题排查求助

Fixing the "null" Output Issue in Your Longest Common Prefix C++ Code

Hey there! Let's break down why your custom str function is returning a seemingly null value, even though printing inside the loop looks correct. I'll walk you through the root cause and easy fixes.

The Root Problem: Undefined Behavior in Your str Function

Look closely at how you're initializing and modifying the result string:

string str(string s, int mid){ 
    string result; // This creates an EMPTY string (length = 0)
    for(int j=0;j<=mid;j++){ 
        result[j]= s[j]; // ❌ Accessing out-of-bounds memory!
    } 
    return result; 
}

When you create string result;, it starts with a length of 0. Assigning to result[j] directly writes to memory that doesn't belong to the string—this is undefined behavior.

The reason printing inside the loop might look okay is that the memory you're writing to hasn't been overwritten yet. But once the function returns, the corrupted string state becomes visible (showing as null or garbage data).

Simple Fixes for the str Function

You have a few clean ways to fix this:

1. Pre-allocate the String's Length

Initialize result with enough space upfront so you can safely assign to indices:

string str(string s, int mid){ 
    string result(mid + 1, ' '); // Allocate mid+1 characters
    for(int j=0;j<=mid;j++){ 
        result[j] = s[j]; 
    } 
    return result; 
}

2. Build the String Safely with push_back

Let the string handle its own resizing by adding characters one at a time:

string str(string s, int mid){ 
    string result; 
    for(int j=0;j<=mid;j++){ 
        result.push_back(s[j]); // Automatically expands the string
        // Alternatively: result += s[j];
    } 
    return result; 
}

3. Use C++'s Built-in substr Method (Best Option)

Skip writing your own loop entirely—C++ strings have a built-in method to get substrings:

string str(string s, int mid){ 
    return s.substr(0, mid + 1); // substr(start_pos, length)
}

This is the most concise and least error-prone approach.

Bonus: Minor Improvements for Your Full Code

While we're at it, here are a couple of small tweaks to make your code more robust:

  • Replace returns of " " with "" (empty string) — a non-existent common prefix should return empty, not a space.
  • Rename variables min and max to low and high — these names clash with standard library functions in <algorithm>.
  • Add a check for empty input (if strs is empty, return immediately to avoid accessing strs[0]).

Final Note

Once you fix the str function, your printed temp value should show the correct substring instead of null. The binary search approach for longest common prefix is a smart choice—nice work there!

内容的提问来源于stack exchange,提问作者Bibin Eugine

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 20:47:44