-
Unknown Stack corruption
Hello, everyone.
I'm having a problem with a corrupted stack and I have no idea what the problem is.
I defined a function to receive a character as input and spit out a binary representation in a string:
Code:
string to_binary_c(char c)
{
int k = 0;
unsigned char j, i = static_cast<unsigned char>(c);
string t;
for(((j = ~0U) >>= 1)++; j > 0; j >>= 1, k++)
i & j ? t += '1' : t += '0';
return t;
}
If I ignore the compiler warning, there's nothing wrong with the result, but it keeps telling me that, "the stack around the variable j has been corrupted."
BTW, I'm calling the function from within another function which does the same thing as the above but only does it with a character pointer:
Code:
string to_binary_cp(char* cp)
{
int k = 0, s_len = strlen(cp);
string t, u;
for(int i = 0; i < s_len; i++)
{
u = to_binary_c(cp[i]);
u += '-';
t += u;
}
t.resize(t.size() - 1, '\0');
return t;
}
Any help would be appreciated.
-
Made a couple changes to your function:
Code:
string to_binary_c(char c)
{
unsigned char j(128), i = static_cast<unsigned char>(c);
string t;
for(; j > 0; j >>= 1)
i & j ? t += '1' : t += '0';
return t;
}
This can also be done using a bitset:
Code:
#include <bitset>
using namespace std;
...
string to_binary_c(char c)
{
return bitset<8>(c).to_string();
}
-
i dont get any warnings at all except an unused var from gcc -Wall.. what compiler are you using.. also could it be that you never initialize j?
or
what if you use this in place of the for in to_bin_c
for( ; c; c <<= 1) c & 128 ? t += '1' : t += '0';