Помощ за малко C++ код

Verdant

New Member
Кода е предназначен да функционира като прочетете файла на блокове от по около 256 байта. 256 байта се разбиват в 8 части след това се изпращат в системата на ядрото, където се преработват.
Това е теорията обаче преминаването от единична нишка до 8 не работи добре. Ако някой може да ми обясни от къде идва грешка ще съм благодарен.


<code>
// This class is for Tea the cypher that does not need to be linked
class stringTeaCypher
{
private:
void decodeXtea(unsigned int* v, unsigned int* w, unsigned int* k) {
register unsigned int v0=v[0], v1=v[1], i, sum=0xC6EF3720;
register unsigned int delta=0x9E3779B9;
for(i=0; i<32; i++) {
v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]);
sum -= delta;
v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
}
w[0]=v0; w[1]=v1;
}
void encodeXtea(unsigned int* v, unsigned int* w, unsigned int* k) {
register unsigned int v0=v[0], v1=v[1], i, sum=0;
register unsigned int delta=0x9E3779B9;
for(i=0; i<32; i++) {
v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
sum += delta;
v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]);
}
w[0]=v0; w[1]=v1;
}
void TeaDecode ( const std::string& str, const std::string& key, std::string* out )
{
unsigned int v[2];
unsigned int w[2];
unsigned int k[4];
unsigned int keybuffer [ 4 ];

// Clear buffers
memset ( v, 0, sizeof(v) );
memset ( w, 0, sizeof(w) );
memset ( k, 0, sizeof(k) );
memset ( keybuffer, 0, sizeof(keybuffer) );
out->clear ();

// Count the number of passes that we need
int numBlocks = str.length() / 4;
int numPasses = numBlocks - 1;

if ( numPasses <= 0 )
return;

// Process the key
int len = key.length ();
if ( len > 16 )
len = 16;
memcpy ( keybuffer, key.c_str(), len );
for ( int i = 0; i < 4; ++i )
k = keybuffer;

// Create a temporary buffer to store the result
unsigned char* buffer = new unsigned char [ numPasses * 4 + 4 ];
memset ( buffer, 0, numPasses * 4 + 4 );

// Decode it!
const char* p = str.c_str();
v[1] = *(unsigned int*)&p[numPasses * 4];
for ( int i = 0; i < numPasses; ++i )
{
v[0] = *(unsigned int*)&p[(numPasses-i-1)*4];
decodeXtea ( &v[0], &w[0], &k[0] );
*(unsigned int*)&buffer[(numPasses-i-1)*4] = w[0];
v[1] = w[1];
}

out->assign ( (char *)buffer, numPasses*4 );
delete [] buffer;
}
void TeaEncode ( const std::string& str, const std::string& key, std::string* out )
{
unsigned int v[2];
unsigned int w[2];
unsigned int k[4];
unsigned int keybuffer [ 4 ];

// Clear buffers
memset ( v, 0, sizeof(v) );
memset ( w, 0, sizeof(w) );
memset ( k, 0, sizeof(k) );
memset ( keybuffer, 0, sizeof(keybuffer) );
out->clear ();

// Process the key
int len = key.length ();
if ( len > 16 )
len = 16;
memcpy ( keybuffer, key.c_str(), len );
for ( int i = 0; i < 4; ++i )
k = keybuffer;

// Copy the input string to a buffer of size multiple of 4
int strbuflen = str.length ();
if ( strbuflen == 0 )
return;
if ( (strbuflen % 4) > 0 )
strbuflen += 4 - (strbuflen % 4);
unsigned char* strbuf = new unsigned char [ strbuflen ];
memset ( strbuf, 0, strbuflen );
memcpy ( strbuf, str.c_str(), str.length() );

// Encode it!
v[1] = 0;
for ( int i = 0; i < strbuflen; i += 4 )
{
v[0] = *(unsigned int*)&strbuf;

encodeXtea ( &v[0], &w[0], &k[0] );
out->append ( (char*)&w[0], 4 );

v[1] = w[1];
}
out->append ( (char*)&v[1], 4 );

delete [] strbuf;
}
public:
void encode(string inString,string key,string &out)
{
TeaEncode(inString,key,&out);
}
void decode(string inString,string key,string &out)
{
TeaDecode(inString,key,&out);
}
};
// The other stuff put into a class
class Core
{
private:
string theMainBuffer;
vector <string> ram;
long int encodeSize,decodeSize,bufferSize;
string mode;
string key;
size_t count;
int getSizeOfString(string theString)
{
return theString.length();
}
void cores(int rRam)
{
string ramTemp("");
//stringAesCypher Code;
stringTeaCypher Code;

if(mode == "E")
{
Code.encode(ram[rRam],key,ramTemp);
}
if(mode == "D")
{
Code.decode(ram[rRam],key,ramTemp);
}
ram[rRam] = ramTemp;
}
void startCores()
{
thread coreSet[8];
for(int i = 0; i != 8; i++){coreSet = thread(&Core::cores,this,i);}
for(int i = 0; i != 8; i++){coreSet.join();}
}
vector<string> breakSplit(const string& raw)
{
size_t bins = 8;
size_t rawlen = raw.size();
size_t div = rawlen / bins;
size_t excess = rawlen % bins;
auto pos = raw.cbegin();
vector<string> fragments(bins);
for(size_t i = 0; i < bins; ++i) {
// the first few bins get one of the excess char each
size_t binlen = div + (i < excess ? 1 : 0);
auto nextpos = pos + binlen;
fragments = string(pos, nextpos);
pos = nextpos;
}
return fragments;
}
void unsplitData()
{
theMainBuffer = "";
for(int i = 0; i != 8; i++)
{
theMainBuffer.append(ram);
cout << getSizeOfString(ram) << endl;
ram = "";
}
}
public:
Core();
void setMode(string theMode)
{
mode = theMode;
}
void setKey(string theKey)
{
key = theKey;
}
void readFile(string inputFileName,string outputFileName)
{
int theSize(0);
if(mode == "E"){theSize = encodeSize;}
if(mode == "D"){theSize = decodeSize;}
// Size and file streams
ifstream fileStreamIn(inputFileName,ios::binary);
ofstream fileStreamOut(outputFileName,ios::binary);
// The main loop
while(fileStreamIn)
{
fileStreamIn.read(&theMainBuffer.front(),theSize);// Reads
count = fileStreamIn.gcount();// Read ammount
theMainBuffer.resize(count);
ram = breakSplit(theMainBuffer);
startCores();
unsplitData();

fileStreamOut.write(theMainBuffer.c_str(),theMainBuffer.length()); // write
//cout << "Data in flow " << count << " Data encoder outflow " << theMainBuffer.length() << endl;
}
fileStreamIn.close();
fileStreamOut.close();
}
};

Core::Core()
{
encodeSize = 256;
decodeSize = 288;
bufferSize = 360;
ram.resize(8);
theMainBuffer.resize(bufferSize);
}

</code>
 
От: Помощ за малко C++ код

while( fileStreamIn.read(&theMainBuffer.front(), theSize) )
{
}

Можеш да пробваш stream output.
 
От: Помощ за малко C++ код

Тествах тази функция още в началото и мислех да се спирам на нея но мисля, че всичко по нея работи както трябва.
 
От: Помощ за малко C++ код

Провери read file променливата, която се изполва с string main buffer. Пробва ли да го дебъгнеш и да видиш на кой ред прави проблема?
 
От: Помощ за малко C++ код

Разбира се! Еми ще тествам това което ми написа последно да проверя как се съхранява в меморито предполагам, че е възможно от там да идва проблема.
 
От: Помощ за малко C++ код

Разбира се! Еми ще тествам това което ми написа последно да проверя как се съхранява в меморито предполагам, че е възможно от там да идва проблема.

Отделно има възможност да е заради stringmainBuffer === NULL ?
 
От: Помощ за малко C++ код

Отделно има възможност да е заради stringmainBuffer === NULL ?

#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main ()
{
string fileName,txt;
cin>>fileName;
ifstream file;
file.open(fileName);
while(file.good())
{file>>txt;}
file.close();
system("pause");
cout << "free" << endl;
system("pause");
}

От този пример няма да има memory leak. Ако ще ползваш примера премахни fileName() !
 
От: Помощ за малко C++ код

#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main ()
{
string fileName,txt;
cin>>fileName;
ifstream file;
file.open(fileName);
while(file.good())
{file>>txt;}
file.close();
system("pause");
cout << "free" << endl;
system("pause");
}

От този пример няма да има memory leak. Ако ще ползваш примера премахни fileName() !

Добре ще направя няколко теста след малко и ще ти пиша.
 
От: Помощ за малко C++ код

while(fileStreamIn) този цикъл в мейн функцията ако можеш също го пренапиши, защото използва прекалено много ресурси.
 
От: Помощ за малко C++ код

// This class is for Tea the cypher that does not need to be linked
class stringTeaCypher
{
private:
void decodeXtea(unsigned int* v, unsigned int* w, unsigned int* k) {
register unsigned int v0=v[0], v1=v[1], i, sum=0xC6EF3720;
register unsigned int delta=0x9E3779B9;
for(i=0; i<32; i++) {
v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]);
sum -= delta;
v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
}
w[0]=v0; w[1]=v1;
}
void encodeXtea(unsigned int* v, unsigned int* w, unsigned int* k) {
register unsigned int v0=v[0], v1=v[1], i, sum=0;
register unsigned int delta=0x9E3779B9;
for(i=0; i<32; i++) {
v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
sum += delta;
v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]);
}
w[0]=v0; w[1]=v1;
}
void TeaDecode ( const std::string& str, const std::string& key, std::string* out )
{
unsigned int v[2];
unsigned int w[2];
unsigned int k[4];
unsigned int keybuffer [ 4 ];

// Clear buffers
memset ( v, 0, sizeof(v) );
memset ( w, 0, sizeof(w) );
memset ( k, 0, sizeof(k) );
memset ( keybuffer, 0, sizeof(keybuffer) );
out->clear ();

// Count the number of passes that we need
int numBlocks = str.length() / 4;
int numPasses = numBlocks - 1;

if ( numPasses <= 0 )
return;

// Process the key
int len = key.length ();
if ( len > 16 )
len = 16;
memcpy ( keybuffer, key.c_str(), len );
for ( int i = 0; i < 4; ++i )
k = keybuffer;

// Create a temporary buffer to store the result
unsigned char* buffer = new unsigned char [ numPasses * 4 + 4 ];
memset ( buffer, 0, numPasses * 4 + 4 );

// Decode it!
const char* p = str.c_str();
v[1] = *(unsigned int*)&p[numPasses * 4];
for ( int i = 0; i < numPasses; ++i )
{
v[0] = *(unsigned int*)&p[(numPasses-i-1)*4];
decodeXtea ( &v[0], &w[0], &k[0] );
*(unsigned int*)&buffer[(numPasses-i-1)*4] = w[0];
v[1] = w[1];
}

out->assign ( (char *)buffer, numPasses*4 );
delete [] buffer;
}
void TeaEncode ( const std::string& str, const std::string& key, std::string* out )
{
unsigned int v[2];
unsigned int w[2];
unsigned int k[4];
unsigned int keybuffer [ 4 ];

// Clear buffers
memset ( v, 0, sizeof(v) );
memset ( w, 0, sizeof(w) );
memset ( k, 0, sizeof(k) );
memset ( keybuffer, 0, sizeof(keybuffer) );
out->clear ();

// Process the key
int len = key.length ();
if ( len > 16 )
len = 16;
memcpy ( keybuffer, key.c_str(), len );
for ( int i = 0; i < 4; ++i )
k = keybuffer;

// Copy the input string to a buffer of size multiple of 4
int strbuflen = str.length ();
if ( strbuflen == 0 )
return;
if ( (strbuflen % 4) > 0 )
strbuflen += 4 - (strbuflen % 4);
unsigned char* strbuf = new unsigned char [ strbuflen ];
memset ( strbuf, 0, strbuflen );
memcpy ( strbuf, str.c_str(), str.length() );

// Encode it!
v[1] = 0;
for ( int i = 0; i < strbuflen; i += 4 )
{
v[0] = *(unsigned int*)&strbuf;

encodeXtea ( &v[0], &w[0], &k[0] );
out->append ( (char*)&w[0], 4 );

v[1] = w[1];
}
out->append ( (char*)&v[1], 4 );

delete [] strbuf;
}
public:
void encode(string inString,string key,string &out)
{
TeaEncode(inString,key,&out);
}
void decode(string inString,string key,string &out)
{
TeaDecode(inString,key,&out);
}
};
// The other stuff put into a class
class Core
{
private:
string theMainBuffer;
vector <string> ram;
long int encodeSize,decodeSize,bufferSize;
string mode;
string key;
size_t count;
int getSizeOfString(string theString)
{
return theString.length();
}
void cores(int rRam)
{
string ramTemp("");
//stringAesCypher Code;
stringTeaCypher Code;

if(mode == "E")
{
Code.encode(ram[rRam],key,ramTemp);
}
if(mode == "D")
{
Code.decode(ram[rRam],key,ramTemp);
}
ram[rRam] = ramTemp;
}
void startCores()
{
thread coreSet[8];
for(int i = 0; i != 8; i++){coreSet = thread(&Core::cores,this,i);}
for(int i = 0; i != 8; i++){coreSet.join();}
}
vector<string> breakSplit(const string& raw)
{
size_t bins = 8;
size_t rawlen = raw.size();
size_t div = rawlen / bins;
size_t excess = rawlen % bins;
auto pos = raw.cbegin();
vector<string> fragments(bins);
for(size_t i = 0; i < bins; ++i) {
// the first few bins get one of the excess char each
size_t binlen = div + (i < excess ? 1 : 0);
auto nextpos = pos + binlen;
fragments = string(pos, nextpos);
pos = nextpos;
}
return fragments;
}
void unsplitData()
{
theMainBuffer = "";
for(int i = 0; i != 8; i++)
{
theMainBuffer.append(ram);
cout << getSizeOfString(ram) << endl;
ram = "";
}
}
public:
Core();
void setMode(string theMode)
{
mode = theMode;
}
void setKey(string theKey)
{
key = theKey;
}
void readFile(string inputFileName,string outputFileName)
{
int theSize(0);
if(mode == "E"){theSize = encodeSize;}
if(mode == "D"){theSize = decodeSize;}
// Size and file streams
ifstream fileStreamIn(inputFileName,ios::binary);
ofstream fileStreamOut(outputFileName,ios::binary);
// The main loop
while(fileStreamIn)
{
fileStreamIn.read(&theMainBuffer.front(),theSize);// Reads
count = fileStreamIn.gcount();// Read ammount
theMainBuffer.resize(count);
ram = breakSplit(theMainBuffer);
startCores();
unsplitData();

fileStreamOut.write(theMainBuffer.c_str(),theMainBuffer.length()); // write
//cout << "Data in flow " << count << " Data encoder outflow " << theMainBuffer.length() << endl;
}
fileStreamIn.close();
fileStreamOut.close();
}
};

Core::Core()
{
encodeSize = 256;
decodeSize = 288;
bufferSize = 360;
ram.resize(;
theMainBuffer.resize(bufferSize);
}

Това го тествах на Visual Studio 2015 Community, компилира се и работи добре!
 

Горе