ConsoleApplication2.exe中的首次机会异常:0xC0000005:写入访问冲突,c++

First-chance exception in ConsoleApplication2.exe: 0xC0000005: Access violation writing, c++

本文关键字:0xC0000005 访问冲突 c++ 异常 exe 机会 ConsoleApplication2      更新时间:2023-10-16

我正在玩一些代码,并试图使其工作,但似乎我错过了一些东西。。。有人能告诉我我错过了什么或做错了什么吗?程序在中断*(sData->pFileBuffer+i) ^=*(sData->pKey+j);

以下是完整的代码:我正在visual studio 2012中编译,如果这与它有关的话…

#include <iostream>
using namespace std;
/*
struct StubData{
char * pFileBuffer;
long long FileSize;
char * pKey;
long KeySize;
};*/

class StubData{
public:
    char *pFileBuffer;
    long long FileSize;
    char *pKey;
    long KeySize;
    StubData(){}
 };


void Decrypt(StubData * sData){
    int i=0,j=0; 

for(i;i<sData->FileSize;i++){
    *(sData->pFileBuffer+i) ^=*(sData->pKey+j);
    j++;
    if (j>=sData->KeySize)j=0;
}
}

void Encrypt(StubData * sData){
    int i,j;
    sData->pKey="mysecretpassword";
    sData->KeySize=strlen(sData->pKey);
    j=0;
    printf("[*]Encodingn");  
    for(i=0;i<sData->FileSize;i++)
    {
        *(sData->pFileBuffer+i) ^=*(sData->pKey+j);
        j++;
        if (j>=sData->KeySize)j=0;
    }
}

void main(){
    //StubData S;
    StubData *S = (StubData *)malloc(sizeof(StubData));
    new (S) StubData;
    S->pFileBuffer="MARKO";
    S->FileSize=strlen(S->pFileBuffer);
    Encrypt(S);
    cout<<"nencn"<<S->pFileBuffer;
    Decrypt(S);
    cout<<"ndecn"<<S->pFileBuffer;
}

您为S->pFileBuffer 分配一个字符字符串文字

S->pFileBuffer="MARKO";

这些字符串文字是不可变的(通常编译为.rodata)。如果你想要一个可变的字符串,你应该把它分配到某个地方。

你可以做一些类似的事情

char str[] = "MARKO";  //be careful, if this goes out of scope before S, then S has a dangling pointer
S->pFileBuffer=str;

这不是很像C++。但是您的代码的其余部分看起来也不太像C++。