c (arduino) misc function returning char pointer - c++

i found function in some code. Looks like that function generates some random number with variable length and returns char*
char* result = (char*)malloc(sizeof(char)*length);
randomSeed(analogRead(A0));
for (int i = 0; i < length; ++i)
{
result[i] = 48 + random(9);
}
result[length] = '\0';
When i tested it, i was surprised that this code works
But in theory char* is read only data, so this accessing to the elements should be incorrect.
Could someone explain it to me?
I think it will be better that the creator will use char array and then copy that memory to the char*
(i do not have link to code)

first of all your code does not work. You write outside the array in this line
result[length] = '\0';
the code shuold look like:
for (int i = 0; i < length - 1; ++i)
{
result[i] = 48 + random(9);
}
result[length - 1] = '\0';
char is just an integer type and it can be read or written.
if you want make it not writable (at least from the C++ point of view) you need to declare it as const.
const char a;
const char *ptr1;
char * const ptr2;
const char * const ptr3;
where:
ptr1 is a pointer to const char
ptr2 is a const pointer to char
ptr2 is a const pointer to const char

Related

How to write a int* to char[]?

I have
int some_var = 5;
int* ref_on_var = &a;
char arr[8];
char* to_write = reinterpret_cast<char*>(&ref_on_var);
I want to write ref_on_var to arr so i write this
for(size_t i = 0; i < sizeof(int*); ++i)
{
arr[i] = to_write[i];
}
This writes some bytes to array but when I try to get pointer back by
int* get = reinterpret_cast<int*>(arr);
I get incorrect address.
So what do I do wrong?
arr
This evaluates to a pointer to arr, that's the result of using the name of an array in a C++ expression.
This char buffer contains an int *, therefore this must be an int **. So:
int* get = *reinterpret_cast<int**>(arr);

Generate random char/digit

I`m trying to found fastest way to generate random digit/char array.
char *randomGet(int num) {
srand(time(NULL));
const char ab[37] = { "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ" };//Alphabet&Digit
char *targ = new char[num];
for (int i = 0; i < num; i++) {
strcat(targ, ab[rand() % 38]);
}
return targ;
}
So far I've come up with this, but it does not work (argument of type char is incompatible with parameter of type const char *).
Help me find the best solution to my problem. Ty.
strcat() takes a char* as input, but you are giving it a single char instead, thus the compiler error.
Also, the buffer that strcat() writes to must be null terminated, but your targ buffer is not null terminated initially, and you are not allocating enough space for a final null terminator anyway.
You don't need to use strcat() at all. Since you are looping anyway, just use the loop counter as the index where to write in the buffer:
Also, you are using the wrong integer value when modulo the return value of rand(). You are producing a random index that may go out of bounds of your ab[] array.
Try this instead:
char *randomGet(int num)
{
srand(time(NULL));
static const char ab[] = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ"; //Alphabet&Digit
char *targ = new char[num+1];
for (int i = 0; i < num; ++i) {
targ[i] = ab[rand() % 36];
}
targ[num] = '\0';
return targ;
}
I'd make two changes. First, make the internal source array static:
static const char ab[] = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ";
Note that this version does not specify the array size; the compiler will figure it out from the initializer.
Second, pass in a pointer to the target array:
void randomGet(char* targ, int num) {
static const char ab[] = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ";
for (int i = 0; i < num - 1; ++i)
targ[i] = ab[rand() % (sizeof ab - 1)];
targ[num - 1] = '\0';
}
This way, the caller decides how to allocate memory for the string.

How to set quantity of elements of the char array of a variable

How to set quantity of elements of the char array of a variable?
This is my code:
long int len = strlen(qq);
//char buff[10];
//sprintf(buff, "%d", len);
//MessageBoxA(0,buff,0,0);
char key[len] = "12345678901234567890123456789..";//error
char crypt[len];//error
for (int i = 0; i < len; i++) {
crypt[i] = text[i] ^ key[i];
}
In C++ an array can only be staticly sized using a constant variable that is known at compile time, which your len is not. Note that some compiler extensions DO allow this, as it's allowed in C. But for pure C++ you instead can use dynamic memory allocation (this allocates on the heap instead of the stack):
char* key = new char[len];
char* crypt = new char[len];
Note that a char* can be used the same as a char[] (you can still use array indexing, the rest of your code remains unchanged).
Because the array is now allocated on the heap, to avoid memory leaks you must manually free the memory when you no longer need it using delete e.g. at the end of the function after you loop:
delete[] key;
delete[] crypt;
Since you specified the winapi tag, it may be that the CString class would be a viable solution.
For your key though, you don't even need to allocate an array dynamically. You could use the modulo operator:
static const char key[] = "1234567890";
const size_t keyLength = strlen(key);
CString crypt(0, len);
for (int i = 0; i < len; i++) {
crypt[i] = text[i] ^ key[i & keyLength];
}

C++ Random String return unexpected results

I am trying to use a function to generate a char[] :
char* randString(){
const int len = 5;
char s[len] = {0};
static const char alphanum[] =
"0123456789"
"!##$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
int stringLength = sizeof(alphanum) - 1;
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % stringLength];
}
return s;
}
the result is random and expected at return s
+ s 0x002df990 "XnQWp... char[5]
however, when i look at the value here:
char* rand = randString();
it contains strange values:
+ rand 0x002df990 "XnQWpÌÌÌÌÌÌÌÌÌÌÌ\x5" char *
did I do something wrong in the return?
You're declaring char s[] as a local variable. Local variables are destroyed when the function returns so returning a pointer to that variable returns a pointer pointing to junk data.
Fix this by allocating s dynamically:
char* s = new char[len];
Or you could pass a char* as a parameter and write your character to that array.
Just remember to add the terminating null character before returning.

Can't delete an unsigned char* after inserting data

I have this code
unsigned char _binary[] = {'1','1','1','0','0','0','1','0',NULL};
int length = 0;
for(length=0;_binary[length];length++);
unsigned char *_hexaActual = new unsigned char;
ConvertBinaryToHexaDecimal(_binary, length, _hexaActual);
string _actual((char*)_hexaActual);
delete[] _hexaActual; // crashes here
Now the ConvertBinaryToHexaDecimal is
void ConvertBinaryToHexaDecimal(const unsigned char* _inputBinary, unsigned int _intputLength, unsigned char* _outputHexaDecimal)
{
const unsigned char _hexaDecimalSymbols[16] = {'0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F'};
char* _binary =(char*) malloc(sizeof(char));
int _binaryIndex,_inputIndex;
for(_binaryIndex=0; _binaryIndex < _intputLength%4 ;_binaryIndex++) // padding extra 0's to make the length multiple of 4
_binary[_binaryIndex] = '0';
for(_inputIndex=0; _inputIndex < _intputLength ;_inputIndex++)
_binary[_inputIndex + _binaryIndex] = _inputBinary[_inputIndex];
_binary[_inputIndex + _binaryIndex] = NULL;
_intputLength = _inputIndex + _binaryIndex;
for( _inputIndex=0; _inputIndex < _intputLength; _inputIndex +=4)
{
int _binaryValue = _binary[_inputIndex] - 48;
int _binaryValue1 = _binary[_inputIndex+1] - 48;
int _binaryValue2 = _binary[_inputIndex+2] - 48;
int _binaryValue3 = _binary[_inputIndex+3] - 48;
int _hexValue = _binaryValue3 * 1;
_hexValue += _binaryValue2 * 2;
_hexValue += _binaryValue1 * 4;
_hexValue += _binaryValue * 8;
_outputHexaDecimal[_inputIndex/4] = _hexaDecimalSymbols[_hexValue];
}
_outputHexaDecimal[_inputIndex/4] = NULL;
}
It outputs corretly a hexa decimal value. But when I try to delete it the program crashes.
EDIT: The crash message says HEAP CORRUPTION DETECTED.
You allocated a single unsigned char with new, so you should call delete, not delete []. The latter is for arrays allocated with new [].
You need
delete _hexaActual;
Note that this type of manual allocations and de-allocations are error prone and exception unsafe. It is likely that you can implement your code using standard library containers and algorithms.
Edit: besides that error, you have a few more: The most important one, in the function ConvertBinaryToHexaDecimal, you are passing a pointer to a single unsigned char, but you are treating it like an array:
_outputHexaDecimal[_inputIndex/4] = ....
Next, you hve a memory leak. You allocate here:
char* _binary =(char*) malloc(sizeof(char));
and never call free.
You only allocated one char for _hexaActual, but you are writing many values to it inside ConvertBinaryToHexaDecimal. You need allocate enough space for the characters you are going to put in there. length/4 + 2 should do it.
unsigned char *_hexaActual = new unsigned char[length/4 + 2];