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

C++堆损坏问题求助:string_merge函数返回指针引发内存错误

Fixing Heap Corruption in Your String Merge Program

Hey there! I see you've been stuck on this heap corruption error for days—let's break down the issues in your code and fix them step by step.

First: The Input Handling Quirk

Right after you read t with cin >> t, there's a leftover newline character in the input buffer. When you call cin.getline(S1, T_SIZE) next, it reads that empty newline instead of the actual input line. This can lead to unexpected empty strings in S1 or S2, which messes up the strlen calculations later.

Fix this by adding a cin.ignore() after reading t to skip the newline:

cin >> t; /* number of tests */
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Add this line

(Don't forget to include <limits> for numeric_limits!)

Second: The Loop Logic Causing Heap Corruption

The main culprit behind the heap error is the loop in your string_merge function. Let's look at the first case where strlen(n1) < strlen(k1):

  • You calculate length = 2 * strlen(n1)—this is the total number of characters in the merged string (since you're taking one from each string strlen(n1) times).
  • But your loop runs for (int i = 0; i < length; i++)—that's twice as many iterations as you need! For example, if strlen(n1) is 3, length is 6, so you loop 6 times. By the 3rd iteration, you've already reached the end of n1 and k1, but you keep incrementing them and writing to Merged beyond its allocated space. That's exactly what triggers the heap corruption.

Fixing the Loop

Instead of looping over length, loop over the number of pairs you need to merge—aka the length of the shorter string. This simplifies the code and eliminates the redundant if/else branches:

char * string_merge(char * n, char * k) {
    size_t len_n = strlen(n);
    size_t len_k = strlen(k);
    size_t min_len = min(len_n, len_k);
    size_t merged_len = 2 * min_len;
    
    char *Merged = new char[merged_len + 1];
    Merged[merged_len] = '\0'; // Always set the null terminator first
    
    char *n_ptr = n;
    char *k_ptr = k;
    
    for (size_t i = 0; i < min_len; i++) {
        Merged[2 * i] = *n_ptr++;
        Merged[2 * i + 1] = *k_ptr++;
    }
    
    return Merged;
}

Third: Simplify Input Reading

Your current cin.getline(S1, T_SIZE, ' ') uses a space as the delimiter, which can cause issues if your input has unexpected formatting. Since you're reading pairs of strings separated by spaces, you can use cin directly (it stops at whitespace by default) to avoid buffer quirks:

while(t--) {
    cin >> S1 >> S2; // Reads S1 (until space) then S2 (until newline)
    S = string_merge(S1, S2);
    cout << S << endl;
    delete[] S;
}

Full Fixed Code

Here's the complete corrected code with all the fixes:

#include <iostream>
#include <cstring>
#include <limits> // For numeric_limits
#include <algorithm> // For min()
using namespace std;

#define T_SIZE 1001

char* string_merge(char *, char *);

int main() {
    int t;
    char S1[T_SIZE], S2[T_SIZE], *S;
    cin >> t; /* number of tests */
    cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Skip leftover newline
    
    while(t--) {
        cin >> S1 >> S2;
        S = string_merge(S1, S2);
        cout << S << endl;
        delete[] S;
    }
    return 0;
}

char * string_merge(char * n, char * k) {
    size_t len_n = strlen(n);
    size_t len_k = strlen(k);
    size_t min_len = min(len_n, len_k);
    size_t merged_len = 2 * min_len;
    
    char *Merged = new char[merged_len + 1];
    Merged[merged_len] = '\0';
    
    char *n_ptr = n;
    char *k_ptr = k;
    
    for (size_t i = 0; i < min_len; i++) {
        Merged[2 * i] = *n_ptr++;
        Merged[2 * i + 1] = *k_ptr++;
    }
    
    return Merged;
}

This code fixes the heap corruption by ensuring we never write past the end of the allocated buffer, handles input correctly, and simplifies the logic to make it easier to follow. You should no longer see that error now—happy coding!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:42:41