Memory problem

The following program I wrote is crashing on delete stmt.
I need delete to free  the memory allocated in encrypt().

#include<iostream.h>
#include<string.h>

#define COUNT 4
const int key[ COUNT ] = { 1,2,5,2 };

char* encrypt( char* str )
{
      int length = strlen( str );
      int val =0, num=0;
      char * store = new char[length];

      for( int idx=0; idx< length; idx++){
            if( num==COUNT){
                  num=0;
            }
            val = key[num];
            num++;
            
            char c = str[idx] + val;
            store[idx] = c;
      
      }
      store[length] = 0;
      return store;
}

char* decrypt( char* str );
int main()
{

      char* str = "testtesttest";
      char* str1 = encrypt(str );

      cout<<"Before: "<<str;
      cout<<"After: "<<str1;

      delete str1;//crashing here...why????


      return 0;
}
openujsAsked:
Who is Participating?
 
brettmjohnsonConnect With a Mentor Commented:
>      char * store = new char[length];

You want
     char * store = new char[length+1];

strlen() does not include the NUL terminator in the count.  You need to allocate an extra byte to hold the NUL your assign here:
     store[length] = 0;
0
 
brettmjohnsonCommented:
Oh, and "//crashing here...why????"  Since you overwrote your allocated block by one byte, you corrupted the memory allocation arena, hence the crash when you call delete.
0
 
List244Commented:
You delete an array using:

delete [] ARRAYHERE

NOT

delete ARRAYHERE

Change it to:

delete [] str1;
0
Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

 
List244Commented:
Once you change your delete to delete properly and set your length +1 as BrettMJohnson stated, you should have it compiling.
0
 
openujsAuthor Commented:
thanks guys..
i knew that how did i overlook that.
0
 
List244Commented:
Openujs, in the future, you should use the split points option when more than one persons
comments have helped to solve your problem.
0
 
openujsAuthor Commented:
sure..i need to figure out how to split points.
0
 
List244Commented:
You can not do that on a closed question.  However, when closing a question, there is a link directly above
the type-box (Where you type your message) that says "Split points."  You can use that to split points rather
than accepting just one answer.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.