0

I am getting this error on my delete[] in my code below

string lcs_tree(string sig, string flow)
{
    int l1, l2;
    string getres;

    l1 = sig.length()+1;
    l2 = flow.length()+1;

    char *x, *y;

    x = new char [l1];
    y = new char [l2];

    x = (char*)sig.c_str();
    y = (char*)flow.c_str();

    lcs_length(x, y, l1, l2, getres);

    delete[] x;
    delete[] y;

    return getres;
}

I'm trying to make the delete to free up memory because my program keeps getting killed when I don't free up memory after dynamically creating arrays. My delete works for this section of the code

void lcs_length(char *x,char *y, int l1, int l2, string& getres)
{
int m,n,i,j,**c;

c = new int *[l1];
for(int t = 0; t < l1; t++)
    c[t] = new int [l2];

char **b;

b = new char *[l1];
for(int t = 0; t < l1; t++)
    b[t] = new char [l2];

m=strlen(x);
n=strlen(y);
for(i=0;i<=m;i++)
    c[i][0]=0;
for(i=0;i<=n;i++)
    c[0][i]=0;
for(i=1;i<=m;i++)
    for(j=1;j<=n;j++)
    {
        if(x[i-1]==y[j-1])
        {
            c[i][j]=c[i-1][j-1]+1;
            b[i][j]='c'; //c stands for left upright cross
        }
        else if(c[i-1][j]>=c[i][j-1])
        {
            c[i][j]=c[i-1][j];
            b[i][j]='u'; //u stands for upright or above
        }
        else
        {
            c[i][j]=c[i][j-1];
            b[i][j]='l'; //l stands for left
        }
    }
    print_lcs(b,x,m,n,getres);

for(int t = 0; t < l1; t++)
    delete[] c[t];
delete[] c;

for(int t = 0; t < l1; t++)
    delete[] b[t];
delete[] b;
}

But when I use it in the first section I am getting the invalid pointer error. Why am I getting it there and not the second section?

  • 5
    You allocate new memory. Then you change the pointer and lose that memory. But that's not it. You change it to memory managed by the `std::string` object. And when the compiler complains, you put in a cast to shut it up. Then you mistakenly delete the memory you promised to be extra careful with. – chris Mar 12 '14 at 17:08
  • 1
    @chris... and leak the only two things that *should* be deleted. – WhozCraig Mar 12 '14 at 17:12
  • Dupe of http://stackoverflow.com/questions/7424613/glibc-detected-free-invalid-pointer?rq=1 ? – JF it Mar 12 '14 at 17:24
  • Okay I get it now. I used the strcpy function to put the strings into the character arrays and it works now. Thanks. – Thejthar Mar 12 '14 at 21:11

0 Answers0