Stack around the variable 'uChar' was corrupted - c++

Here is the code which converts a hex string to byte array, it works fine but when the loop goes end and the complier reaches to the end of function it throws this error:
"Stack around the variable 'uChar' was corrupted"
void Cfsp::stringToHex(unsigned char hexArray[], LPCTSTR string)
{
int stringLength=strlen(string);
int j=0;
unsigned char uChar = 0;
for (int x = 0; x < stringLength; x+=2)
{
sscanf_s(&string[x], "%02x", &uChar);
hexArray[j] = uChar;
j++;
}
}
Here is where I initiate the array and call the function.
unsigned char Key[16];
stringToHex( Key,"2f145a8b11d33217");
I know when stringToHex would convert the given string (16 chars length) to byte array it only fills 8 Bytes(as char). I just wanted to make a reserved area in the buffer.

This is why the xxx_s functions are not safe :-) People can misuse these safe functions as easily as the so-called "unsafe" ones.
sscanf with the %x format specifier wants an int pointer, not a char one.
It will write the entire (for example) 32 bit value starting at uChar and not caring one bit what it overwrites in the process.
It's only because you have stack protection enabled that the code catches this.
You should be using something like:
void Cfsp::stringToHex (unsigned char hexArray[], LPCTSTR string) {
int stringLength = strlen (string);
int j = 0;
unsigned int uChar = 0; // <-- INT rather than char.
for (int x = 0; x < stringLength; x+=2) {
sscanf_s (&string[x], "%02x", &uChar);
hexArray[j] = uChar;
j++;
}
}

The reason you get corruption is because you send sscanf_s an unsigned char * where it expects int *

I don't know how sscanf_s works, but from the sscanf manpage:
x Matches an unsigned hexadecimal integer; the next pointer must be a pointer to unsigned int.

The error is probably caused by "%02x" which requires an int as storage, not an unsigned char.
The issue could also be that you called strlen(LPCTSTR). LPCTSTR might or might not have a terminating zero, if it doesn't strlen invokes undefined behaviour. Use _tcslen(LPCTSTR) instead.

Related

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 iterate through the bytes of a void* in C++?

What would be the best way to iterate through each byte of a void* buffer, and a assign a value to each depending on certain conditions?
unsigned int bufSize = 100; //could be any value
void* buffer = malloc(bufSize);
char* bufferPointer = static_cast<char*>(buffer);
for (unsigned int i = 0; i < bufSize; i++){
if (i % 2 == 0){
bufferPointer[i] = 0x00;
}
else{
bufferPointer[i] = 0xff;
}
}
buffer = static_cast<void*>(bufferPointer);
Why doesn't this work? I tried converting to a char* to iterate over each byte.
You need to cast the void* to an unsigned char*. You can then use pointer arithmetic to traverse the block of memory that you own, and set values by pointer dereference.
Remember that pointer arithmetic is only valid within arrays. For this purpose an object can be considered to be an array of length 1. Also, and perhaps confusingly, an array of N int elements will equate to an array of N * sizeof(int) unsigned char elements.

c++ passing array through function [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sizeof an array in the C programming language?
I've been fiddling with C to become better acquainted with it and think I may have stumbled upon a initialization/pointer issue that I'm unsure of how to resolve. The below program is an implementation of ROT13, so it takes an input string, and shifts each letter by 13, resulting in the cipher text. The output of my program displays the correct shift, but it won't work for more than 4 characters, making me wonder if sizeof is being used incorrectly. Any other suggestions are appreciated, I'm sure I've messed a few things up at this point.
#include <stdio.h>
#include <string.h>
void encrypt(char *);
int main(void){
char input[] = "fascs";
encrypt(input);
return 0;
}
void encrypt(char *input){
char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
printf("Input: %s \n", input);
int inputCount = sizeof(input);
printf("Characters in Input: %i \n\n", inputCount);
//holds encrypted text
char encryptedOutput[inputCount];
//Initialize counters
int i, j = 0;
// loop through alphabet array, if input=current letter, shift 13 mod(26),
// push result to output array, encryptedOutput
for(i = 0; i < inputCount; i++){
for(j = 0; j < 26; j++){
if(input[i] == alphabet[j]){
encryptedOutput[i] = alphabet[(j + 13) % 26];
}
}
}
//Nul Termination for printing purposes
encryptedOutput[i] = '\0';
printf("Rot 13: %s \n\n", encryptedOutput);
}
sizeof() in encrypt will not behave as you want it to. Inside encrypt, the sizeof(char *) is 4(on a 32bit machine) or 8(on a 64 bit machine), which you can see is the size of a pointer.
To get the sizeof(input) you must change sizeof to strlen. Hence solution = strlen(input)
Why this happens?? when you pass an array into a function, that array is internally represented as a pointer. At the called-function's end input is just a pointer, which gives either 4 or 8 bytesize depending upon your machine.
To get the sizeof of input, just use a macro like this:
#define SIZEOF(x) (sizeof(x)/sizeof(x[0]))
and use this in the function that defines x. In your program, x is input in main()
sizeof returns the size of the type of its argument. It cannot determine how many characters are in a pointer to a character array.
You should consider using the strlen function if you know that your string is null-terminated.
input has type char* (read as "pointer to char"). sizeof(input) gives you the size of the pointer. You probably want to use strlen to find the length of the string, or pass the length in to the function as an additional argument.
This line causes your problem.
int inputCount = sizeof(input);
sizeof only determines the size of the variable in this case char *. And every pointer has the size of 4 bytes on a 32 bit system.
You can't determine the size of an array during runtime. You could either
* pass the size of the input as an parameter
* because in your case it is a string, use the strlen in string.h to get the length of the string if the string is terminated by \0.
But in both cases you can't simply allocate the output buffer using
char output[variable_containing_size];
You would need to use malloc() to dynamically allocate memory during runtime or even easier pass the output parameter as parameter to your function.
#include <stdio.h>
#include <string.h>
#define BUFFER_LENGTH 80
void encrypt(const char * input, char *output);
int main(void){
char input[BUFFER_LENGTH] = "fascs";
char output[BUFFER_LENGTH] = {0}; // initialize every field with \0
encrypt(input, output);
return 0;
}
void encrypt(const char *input, char *output){
char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
printf("Input: %s \n", input);
int inputCount = strlen(input);
printf("Characters in Input: %i \n\n", inputCount);
//Initialize counters
int i, j = 0;
// loop through alphabet array, if input=current letter, shift 13 mod(26),
// push result to output array, output
for(i = 0; i < inputCount; i++){
for(j = 0; j < 26; j++){
if(input[i] == alphabet[j]){
output[i] = alphabet[(j + 13) % 26];
}
}
}
//Nul Termination for printing purposes
output[i] = '\0';
printf("Rot 13: %s \n\n", output);
}
But in this case the encrypt() function does no size checks at all, and if you're not careful this could easily lead to buffer overflows.

C++ copying memory from one type to another [duplicate]

This question already has answers here:
Converting byte array (char array) to an integer type (short, int, long)
(5 answers)
Closed 7 years ago.
I'd like to save the bit values of a char[4] into an int.
Say "aaaa" is the string, I'd like the int to be 1633771873.
'a' is stored as 01100001 on one byte in memory, so "aaaa" is
01100001 01100001 01100001 01100001, or 32 bits, which should fit into an int, and its decimal value is 1633771873.
How do I copy the bit value of my char[4] into the memory of the int ?
You can use std::memcpy(void* dest, const void* src, std::size_t count) like
std::memcpy(&my_int, my_char, 4);
I would suggest the best solution for this specific case:
union U
{
char c[4];
int i;
};
Use it:
char arr[4] = "aaaa";
U u;
u.c[0] = arr[0];
u.c[1] = arr[1];
u.c[2] = arr[2];
u.c[3] = arr[3];
std::cout<< u.i; //use it
Unions also solve problem with endiannes (because layout of bytes in union will be platform-specific).
This can be done by shifting each element of the char array and summing them up:
#include <iostream>
int main()
{
const char* a = "aaaa";
unsigned int result = 0;
for(int i = 0; i< 4; ++i)
{
result += ((unsigned int)a[i]) << (32-i*8);
}
std::cout<< result;
return 0;
}
Obviously memcpy would be good for this, but I don't think it is really good idea to write that kind of code. It depends on your CPU architecture, becouse your integer will be different on Little Endian and Big Endian CPUs.
Obviously not in this case, where all bytes are the same, but in general.
What about this,
const char *pcString = "aaaa";
int *ptrToInt = new int();
memcpy(ptrToInt, pcString, 4);

How to manage passing a pointer to an array to a function

I have a buffer of points that I want to send off to be processed by a function. It is an array of unsigned shorts. Currently I'm trying the following:
void ftn(unsigned short **buffer, int size)
{
for (int i = 0; i < size; i++)
{
*(buffer[i]) = 0; //test
}
}
Outside of the function, it's defined as unsigned short buffer[size]; Does this not make sense? Where am I going wrong? Thanks
When you pass an array to a function, you don't actually pass the array by value. Rather, you actually pass a reference to the original array.
Therefore, you simply need to do:
void ftn(unsigned short buffer[], int size)
{
for (int i = 0; i < size; i++)
{
buffer[i] = 0; //test
}
}
Note that if you change the actual value of buffer, you don't actually change the original array. An example of this could be:
void ftn(unsigned short buffer[], int size)
{
buffer = new unsigned short[20];
}
If you wish to change the original array, your construct will work, but with a little modification:
void ftn(unsigned short **buffer, int size)
{
for (int i = 0; i < size; i++)
{
(*buffer)[i] = 0; //test
}
}
This is very C-like, mind you, and less C++-like.
buffer is a pointer to a pointer to an unsigned short. (That is, a pointer to the variable you use to refer to the array.)
If you dereference buffer, you get a pointer to an unsigned short, which can be treated as an array of unsigned shorts.
With this you also have the ability to reassign the value of the original variable, for instance like this:
void ftn(unsigned short **buffer, int size)
{
*buffer = new unsigned short[20];
}
See also:
Arrays as parameters
No that doesn't make sense, because buffer[i] "returns" an array of shorts, and the
*(buffer[i]) tries to dereference that array of shorts, and then, you try to set a memory address for that (i.e. NULL or 0), and that results in a seg fault.
The answer is very quick, I don't know why people wrote so much:
#define SIZE_ARRAY 10
void ftn(unsigned short * buffer, int size)
{
for (int i = 0; i < size; i++)
{
buffer[i] = 0; // test
}
}
void main()
{
unsigned short buffer[SIZE_ARRAY];
ftn(&buffer[0], SIZE_ARRAY);
}
I wouldn't take Sebastian's answer he still uses unsigned short **buffer which is just too complication.