堆腐败c ++函数返回一个表指针

我有一个程序,我一直试图自己解决好几天,但仍然不知道我到底做错了什么。 能否请你帮忙? 首先,我认为大惊小怪是关于char表末尾的null,但正如你所看到的,我修正了这个问题,Visual Studio仍然告诉我,我会以某种方式导致堆损坏:

“HEAP CORRUPTION DETECTED:Normal block(#186)at 0x02BAEC90.CTRL detected that the application write to memory after heap buffer buffer。”

感谢所有希望提前帮助初学者的人!

#include <iostream> 
#include <cstring>  
using namespace std;  
#define T_SIZE 1001  
char* string_merge(char *, char *);  
int main()
{  
    int t,n;    
    char S1[T_SIZE], S2[T_SIZE], *S;    
    cin >> t; /* number of tests */   
    cin.getline(S1,T_SIZE);    
    while(t)
    {      
        cin.getline(S1,T_SIZE,' ');     
        cin.getline(S2,T_SIZE);           
        S=string_merge(S1,S2);     
        cout << S << endl;     
        delete[] S;     
        t--;      
    }    

    return 0; 

}

char * string_merge(char * n, char * k)
{
    char *Merged;
    char *n1;
    char *k1;
    n1 = n;
    k1 = k;
    if (strlen(n1) < strlen(k1))
    {
        const int length = (2*strlen(n1));

        Merged = new char[length+1];
        Merged[length] = '';
        for (int i = 0;i < (length);i++)
        {
            Merged[(2*i)] = *n1 ;
            Merged[(2*i) + 1] = *k1 ;
            if (i < (length - 1))
            {
                n1++;
                k1++;
            }


        }

    return Merged;

    }
    else
    {
        const int length = (2 * strlen(k1));
        Merged = new char[length + 1];

        for (int i = 0;i < (length);i++)
        {
            Merged[(2 * i)] = *n1;
            Merged[(2 * i) + 1] = *k1;
            n1++;
            k1++;

        }
        Merged[length] = '';
        return Merged;

    }


}

难道第一个字符串不会以''结尾?

还读了一个数字后

cin >> t; /* number of tests */ 

您应该忽略用于提交数字的换行符,因此请替换第一个getline()

cin.getline(S1,T_SIZE);    
while(t) 
...

cin.ignore();
while(t) 
...
链接地址: http://www.djcxy.com/p/82337.html

上一篇: Heap corruption c++ Function to return a table pointer

下一篇: HEAP CORRUPTION DETECTED: after Normal block