As always, problems with the pointers. I am trying to create a very simple “encryption/decryption” function for char arrays. Yes, I know I can use strings, but I want to improve my knowledge about pointers and make use of simple bytes to achieve a simple task.
So, I created a simple struct like this:
struct text {
char* value;
int size;
}
And I created this simple function:
text encrypt(text decrypted) {
char key = 'X';
for (int i=0; i<decrypted.size; i++) {
decrypted.value[i] = decrypted.value[i] ^ (key + i) % 255);
}
return decrypted;
}
At this point, an experienced C++ programmer should have spot the problem, I think. Anyway, I call this function like this:
...
text mytext;
mytext.value = new char[5];
mytext.value = "Hello";
mytext.size = 5;
mytext = encrypt(mytext);
...
I get, like always, a ‘Segmentation fault(core dumped)’ error. This is Linux, and, of course, g++. What have I done, again? Thanks!
on the second line, you throw away the (handle to the) allocated memory, leaking it, and let
mytext.valuepoint to a string literal. Modifying a string literal is undefined behaviour, and usually crashes, since string literals are often stored in a read-only memory segment.If you insist on using a
char*, you shouldstrncpythe string into the allocated memory (but be aware that it won’t be 0-terminated then, you should better allocate anew char[6]and copy also the 0-terminator).Or let
decryptcreate a newtextthat it returns:But, as you’re using C++,
std::stringwould be a better choice here.