Heap corruption c++ Function to return a table pointer

I've got this problem with a program that I've been trying to solve by myself for days now and still don't know what exactly am I doing wrong. Could you please help? First I thought the fuss is all about the null at the end of the char table, but as you can see I fixed that and Visual Studio still tells me that I cause heap corruption somehow:

"HEAP CORRUPTION DETECTED: after Normal block (#186) at 0x02BAEC90. CRT detected that the application wrote to memory after end of heap buffer."

Thanks to all who wish to help a beginner in advance!

#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;

    }


}

Could it be that the first string doesn't end with ' '?

Also after reading a number

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

you should ignore also the newline that was used to submit the number, so replace the first getline()

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

with

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

上一篇: CSocket ::在MFC应用程序中创建抛出异常

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