C++ Comparison between signed and unsigned integer expressions - c++

I am new to c++. I need help fixing this error:
Item.cpp: In member function ‘char* ict::Item::sku() const’:
Item.cpp:65:36: warning: comparison between signed and unsigned integer
expressions [-Wsign-compare]
This is the part of the code that is giving the error:
//in header file
char m_sku[MAX_SKU_LEN + 1];
//in cpp file
char* Item::sku() const
{
int length = strlen(m_sku);
char *arr = new char[length]();
for (int i = 0; i <= strlen(m_sku); i++) {
arr[i] = m_sku[i];
}
return arr;
}

The most straightforward way to fix this is to make i an unsigned variable instead of a signed one. You can use size_t to match the return type of strlen:
size_t length = strlen(m_sku);
char *arr = new char[length]();
for (size_t i = 0; i <= length; i++) {
arr[i] = m_sku[i];
}
But be careful since this same replacement doesn't work with loops that count down towards 0.
// oops! This is an infinite loop:
for (size_t i = length-1; i >=0; i--) {
arr[i] = m_sku[i];
}

Write a static cast (int)strlen(m_sku) or vice versa std::size_t i = 0.
So that compared items will be the same.

Related

Error: Initialization with '{...}' expected for aggregate object

below is my code which processes the payload[] array and store it's result on myFinalShellcode[] array.
#include <windows.h>
#include <stdio.h>
unsigned char payload[] = { 0xf0,0xe8,0xc8,0x00,0x00,0x00,0x41,0x51,0x41,0x50,0x52,0x51,0x56,0x48,0x31 };
constexpr int length = 891;
constexpr int number_of_chunks = 5;
constexpr int chunk_size = length / number_of_chunks;
constexpr int remaining_bytes = length % number_of_chunks;
constexpr int size_after = length * 2;
unsigned char* restore_original(unsigned char* high_ent_payload)
{
constexpr int payload_size = (size_after + 1) / 2;
unsigned char low_entropy_payload_holder[size_after] = { 0 };
memcpy_s(low_entropy_payload_holder, sizeof low_entropy_payload_holder, high_ent_payload, size_after);
unsigned char restored_payload[payload_size] = { 0 };
int offset_payload_after = 0;
int offset_payload = 0;
for (size_t i = 0; i < number_of_chunks; i++)
{
for (size_t j = 0; j < chunk_size; j++)
{
restored_payload[offset_payload] = low_entropy_payload_holder[offset_payload_after];
offset_payload_after++;
offset_payload++;
}
for (size_t k = 0; k < chunk_size; k++)
{
offset_payload_after++;
}
}
if (remaining_bytes)
{
for (size_t i = 0; i < sizeof remaining_bytes; i++)
{
restored_payload[offset_payload++] = high_ent_payload[offset_payload_after++];
}
}
return restored_payload;
}
int main() {
unsigned char shellcode[] = restore_original(payload);
}
I get the following error on the last code line (inside main function):
Error: Initialization with '{...}' expected for aggregate object
I tried to change anything on the array itself (seems like they might be the problem). I would highly appreciate your help as this is a part of my personal research :)
In order to initialize an array defined with [], you must supply a list of values enclosed with {}, exactly as the error message says.
E.g.:
unsigned char shellcode[] = {1,2,3};
You can change shellcode to be a pointer if you want to assign it the output from restore_original:
unsigned char* shellcode = restore_original(payload);
Update:
As you can see in #heapunderrun's comment, there is another problem in your code. restore_original returns a pointer to a local variable, which is not valid when the function returns (a dangling pointer).
In order to fix this, restore_original should allocate memory on the heap using new. This allocation has to be freed eventually, when you are done with shellcode.
However - although you can make it work this way, I highly recomend you to use std::vector for dynamic arrays allocated on the heap. It will save you the need to manually manage the memory allocations/deallocations, as well as other advantages.
You can't assign a char * to a char []. You can probably do something with constexpr but I'm suspecting an XY problem here.

Comparison between signed and unsigned integer expression for loop error

I was writing a program that went through a string but in the for loop it gave me an error and the answers online that I found used only vectors.
std::string str = "Test";
for (int i = 0, max = str.size; i < max; i++)
std::string::size is a member function, you need to call it:
for (int i = 0, max = str.size(); i < max; i++)
// ^^ here
... and in order to make the issue with signed-unsigned conversion go away:
for (std::size_t i = 0, max = str.size(); i < max; i++)
// ^^^^^^^^^^^ index type for standard library container
Besides, if you need to process every char in the string, consider using a range based for loop;
for (char c : str)
// ...

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.

C++ expected initializer before '/=' token

I get a error
expected initializer befor '/=' token.
I have
const unsigned in array[]
in my loop, I have:
for (int i = 0; i< length; i++)
{
while (array[i] > 0)
{
const unsigned int array[i] /= 10;
}
}
How can I fix it? Thanks!
const unsigned int array[i] /= 10;
should be:
array[i] /= 10;
If you write a type before a variable name, you perform a variable declaration. This is however not your intention here, you simple want to access it.
I suspect you intend to divide each array entry by 10. I also assume that your gave your array a size (in the brackets). I also assume that length is correct.
Still there are multiple errors.
First the array should be defined unsigned int instead of const unsigned in (remove the const and fix the typo) otherwise it can not be modified.
Then remove the type declaration in the loop and use array[i] /= 10; instead of const unsigned int array[i] /= 10;.
Additionally I wonder why you try to use two nested loops? Simply remove the while loop entirely:
for (int i=0; i<length; i++)
{
array[i] /= 10;
}
I think you have to read a little up on both arrays and in more general C.
When you declare a variable with 'const' it declares it as an constant and therefor it cannot be changed later.
const unsigned int array[]
for (int i = 0; i < length; i++)
{
while (array[i] > 0)
{
const unsigned int array[i] /= 10;
}
}
Should be changed to
unsigned int array[];
for (int i = 0; i < length; i++)
{
if (array[i] > 0)
{
// If array[i] is greater than zero, divide it by 10
array[i] /= 10;
}
}
Ok that was the broad error fixing please checkout those links:
How to initialize all members of an array to the same value?
http://en.wikipedia.org/wiki/Constant_(programming)
Thanks.

why this binary conversion does not work?

#include<stdio.h>
#include<conio.h>
unsigned * bin(unsigned n) {
unsigned a[16];
int i = 0, j = 0;
for (i = 0; i < 16; i++) {
a[i] = n & 0x1;
n = n >> 1;
}
return a;
}
void main() {
unsigned n = 5;
int i = 0;
unsigned * a = bin(n);
for (i = 15; i >= 0; i--) {
printf("%d\n", (*(a + i)));
}
getch();
}
Please help this binary conversion does not work. I'm trying to calculate x^n using binary conversion.
can anybode help??
You are returning a pointer to a local variable. This variable is stored on the stack, and will not be valid after the function returns.
Dereferencing this pointer will lead to undefined behavior.
The solution is to either make the variable static, or pass in the array as an argument to the function, or (as noted in a comment by James Kanze) use a type that copies the contents.
you can not return a local array defined in the function in this way.
The content of the array will be erased when the function finish the execution.
instead of using
unsigned a[16];
you can use the following:
unsigned *a =malloc(16 * (sizeof *a));
And do not forget in your main to free the memory allocated for a when the a array become useless in your program. you can free the array with:
free(a);
Actually, this is a typical case where using new (or malloc) is a pretty bad choice. However, as others have said, returning a pointer to a local array is bad.
Instead, pass in an array:
void bin(unsigned n, unsigned a[]) {
int i = 0;
for (i = 0; i < 16; i++) {
a[i] = n & 0x1;
n = n >> 1;
}
}
and in main:
unsigned a[16];
bin(n, a);
Now you have no need to allocate or return an array from bin.