Friday 15 February 2013

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



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

i'm playing code , trying create work seems i'm missing something... can please tell me did miss or wrong? programme breaks @ *(sdata->pfilebuffer+i) ^=*(sdata->pkey+j);

here total code: i'm compiling in visual studio 2012 if has it...

#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("[*]encoding\n"); 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<<"\nenc\n"<<s->pfilebuffer; decrypt(s); cout<<"\ndec\n"<<s->pfilebuffer; }

you assign charater string literal s->pfilebuffer

s->pfilebuffer="marko";

these character strings literals immutable (often compiled .rodata). if want mutable character string should allocate somewhere.

you can

char str[] = "marko"; //be careful, if goes out of scope before s, s has dangling pointer s->pfilebuffer=str;

this not c++-like. rest of code doesn't seem c++-like either.

c++ pointers access-violation xor

No comments:

Post a Comment