Hello, i really need help on this. I fully cannot understand what i am doing wrong here. This is a segment of my project that uses dynamic arrays but i seem to be getting random memory related crashes that i cannot seem to fix.

These are my encode/decode classes.

They work by XORing every char past the 3nd position by the diffrence between the 1st position XOR 4 and the 2nd postion XOR 6.

My encode class works perfectly, its just my decode class, whenever the array for it to decode is more than 8 numbers it crashes, when it is less it works.

I really cant work this out.. where am i going wrong?

(The code is abit messy through frustration of debugging)

#include <windows.h>
#include <iostream.h>

using namespace std;

int debug = 1;

char * Dec(int * Data, int stringlen){

    char * DecData = new char (stringlen+1);

    cout << "Dec---------------------------\n";    

    int a = (Data[0] ^ 4) ^ 45;
    int b = (Data[1] ^ 6) ^ 17;

    int RecXor = b - a;

    cout << "XorKey = " << RecXor << endl;

    DecData[0] = Data[0] ^ 4;
    DecData[1] = Data[1] ^ 6;

    cout << "0 " << (char)DecData[0] << endl; 
    cout << "1 " << (char)DecData[1] << endl; 

    for(int i = 2;i < stringlen; i++){
            if(debug)
                     cout << i << " " << (char)(Data[i] ^ RecXor) << endl;
            DecData[i] = Data[i] ^ RecXor;  
            cout << stringlen-i << endl;
    }
    delete [] Data;

    DecData[stringlen] = '\0';

    cout << DecData << endl;

    return DecData;
}

int * Enc(char * Data){

    cout << "Enc---------------------------\n";

    if(strlen(Data) < 3){
                    if(debug)
                             cout << "Data is too short to encode\n";

                    return 0;
    }

    int * NewData = new int (strlen(Data));

    NewData[0] = Data[0] ^ 4;
    NewData[1] = Data[1] ^ 6;

    int XorKey = (Data[1] ^ 17) - (Data[0] ^ 45);

    cout << "XorKey = " << XorKey << endl;

    cout << "0 " << NewData[0] << endl;
    cout << "1 " << NewData[1] << endl;

    for(int i = 2; i < strlen(Data);i++){
            NewData[i] = (Data[i] ^ XorKey);
            if(debug)
                     cout << i << " " << NewData[i] << endl;
    }

    delete [] Data;

    return NewData;
}

int main(){

    int * encode = Enc("AAAAAAAA");
    char * decode = Dec(encode, 8);
    system("pause");

    return 0;
}

Thanks in advance for any help

Edited 3 Years Ago by Nick Evan: Fixed formatting

//This
char * DecData = new char (stringlen+1);
//Should be this:
char* DecData = new char[(stringlen+1)];

//This
int * NewData = new int (strlen(Data));
//Should be this:
int* NewData = new int[(strlen(Data))];

Edited 7 Years Ago by Clinton Portis: shake that laffy taffy.

Ah ha! It works!

Such a tiny mistake cost me 3 hours of debugging.

Cheers for the solution

This article has been dead for over six months. Start a new discussion instead.