I am trying to use implement the LSB lookup method suggested by Andrew Grant in an answer to this question: Position of least significant bit that is set
However, it's resulting in a segmentation fault. Here is a small program demonstrating the problem:
#include <iostream>
typedef unsigned char Byte;
int main()
{
int value = 300;
Byte* byteArray = (Byte*)value;
if (byteArray[0] > 0)
{
std::cout<< "This line is never reached. Trying to access the array index results in a seg-fault." << std::endl;
}
return 0;
}
What am I doing wrong?
I've read that it's not good practice to use 'C-Style' casts in C++. Should I use reinterpret_cast<Byte*>(value) instead? This still results in a segmentation fault, though.
Use this:
(Byte*) &value;
You don't want a pointer to address 300, you want a pointer to where 300 is stored. So, you use the address-of operator & to get the address of value.
While Erik answered your overall question, as a followup I would say emphatically -- yes, reinterpret_cast should be used rather than a C-style cast.
Byte* byteArray = reinterpret_cast<Byte*>(&value);
The line should be:
Byte* byteArray = (Byte*)&value;
You should not have to put the (void *) in front of it.
-Chert
char *array=(char*)(void*)&value;
Basically you take a pointer to the beginning of the string and recast it to a pointer to a byte.
#Erik already fixed your primary problem, but there is a subtle one that you still have. If you are only looking for the least significant bit, there is no need to bother with the cast at all.
int main()
{
int value = 300;
if (value & 0x00000001)
{
std::cout<< "LSB is set" << std::endl;
}
return 0;
}
Related
#include <iostream>
int main(){
uint8_t memory[1024];
memory[0] = 1;
memory[1] = 1;
uint32_t *test = memory;
//is it possible to get a value for *test that would be in this example 257?
}
I want to create a uin32_t pointer to the same adress as the uint8_t pointer. Is this possible without using new(adress)? I don't want to lose the information at the adress. I know pointers are just adresses and therefor I should be able to just set the uint32_t pointer to the same adress.
This code produces an error:
invalid conversion from 'uint8_t*' to 'uint32_t*' in initialization
This would be a violation of so-called Strict Aliasing Rule, so it can not be done. Sad, but true.
Use memcpy to copy data and in many cases compilers will optimize memory copy and generate the same code as they would with cast, but in Standard-conforming way.
As already mentioned you cannot convert uint8_t * to uint32_t * due to strict aliasing rule, you can convert uint32_t * to unsigned char * though:
#include <iostream>
int main(){
uint32_t test[1024/4] = {}; // initialize it!
auto memory = reinterpret_cast<unsigned char *>( test );
memory[0] = 1;
memory[1] = 1;
std::cout << test[0] << std::endl;
}
this is not portable code due to Endianness, but at least it does not have UB.
This question completely ignores the concept of endian-ness; while your example has the lower and upper byte the same value, if the byte order is swapped it makes no difference; but in the case where it is; your number will be wrong unexpectedly.
As such, there's no portable way to use the resulting number.
You can do that with union. As mentioned above, you have to be aware of endianness of target device, but in most cases it will be little-endian. And there is also a bit of controversy about using unions in such way, but fwiw it's getting a job done and for some uses it's good enough.
#include <iostream>
int main(){
union {
uint8_t memory[1024] = {};
uint32_t test[1024/4];
};
memory[0] = 1;
memory[1] = 1;
std::cout << test[0]; // 257
}
uint32_t *test =(uint32_t*) memory;
uint32_t shows that the memory pointed by test should contain uint32_t .
I have an array of unsigned integers that need to store pointers to data and functions as well as some data. In the device I am working with, the sizeof pointer is the same as sizeof unsigned int. How can I cast pointer to function into unsigned int? I know that this makes the code not portable, but it is micro controller specific. I tried this:
stackPtr[4] = reinterpret_cast<unsigned int>(task_ptr);
but it give me an error "invalid type conversion"
Casting it to void pointer and then to int is messy.
stackPtr[4] = reinterpret_cast<unsigned int>(static_cast<void *> (task_ptr));
Is there a clean way of doing it?
Edit - task_ptr is function pointer void task_ptr(void)
Love Barmar's answer, takes my portability shortcoming away. Also array of void pointer actually makes more sense then Unsigned Ints. Thank you Barmar and isaach1000.
EDIT 2: Got it, my compiler is thinking large memory model so it is using 32 bit pointers not 16 bit that I was expecting (small micros with 17K total memory).
A C-style cast can fit an octogonal peg into a trapezoidal hole, so I would say that given your extremely specific target hardware and requirements, I would use that cast, possibly wrapped into a template for greater clarity.
Alternately, the double cast to void* and then int does have the advantage of making the code stand out like a sore thumb so your future maintainers know something's going on and can pay special attention.
EDIT for comment:
It appears your compiler may have a bug. The following code compiles on g++ 4.5:
#include <iostream>
int f()
{
return 0;
}
int main()
{
int value = (int)&f;
std::cout << value << std::endl;
}
EDIT2:
You may also wish to consider using the intptr_t type instead of int. It's an integral type large enough to hold a pointer.
In C++ a pointer can be converted to a value of an integral type large enough to hold it. The conditionally-supported type std::intptr_t is defined such that you can convert a void* to intptr_t and back to get the original value. If void* has a size equal to or larger than function pointers on your platform then you can do the conversion in the following way.
#include <cstdint>
#include <cassert>
void foo() {}
int main() {
void (*a)() = &foo;
std::intptr_t b = reinterpret_cast<std::intptr_t>(a);
void (*c)() = reinterpret_cast<void(*)()>(b);
assert(a==c);
}
This is ansi compliant:
int MyFunc(void* p)
{
return 1;
}
int main()
{
int arr[2];
int (*foo)(int*);
arr[0] = (int)(MyFunc);
foo = (int (*)(int*))(arr[0]);
arr[1] = (*foo)(NULL);
}
What is the most simple and efficient why to copy an int to a boost/std::array?
The following seems to work, but I'm not sure if this is the most appropriate way to do it:
int r = rand();
boost::array<char, sizeof(int)> send_buf;
std::copy(reinterpret_cast<char*>(&r), reinterpret_cast<char*>(&r + sizeof(int)), &send_buf[0]);
Just for comparison, here's the same thing with memcpy:
#include <cstring>
int r = rand();
boost::array<char, sizeof(int)> send_buf;
std::memcpy(&send_buf[0], &r, sizeof(int));
Your call whether an explosion of casts (and the opportunity to get them wrong) is better or worse than the C++ "sin" of using a function also present in C ;-)
Personally I think memcpy is quite a good "alarm" for this kind of operation, for the same reason that C++-style casts are a good "alarm" (easy to spot while reading, easy to search for). But you might prefer to have the same alarm for everything, in which case you can cast the arguments of memcpy to void*.
Btw, I might use sizeof r for both sizes rather than sizeof(int), but it sort of depends whether the context demands that the array "is big enough for r (which happens to be an int)" or "is the same size as an int (which r happens to be)". Since it's a send buffer, I guess the buffer is the size that the wire protocol demands and r is supposed to match the buffer, rather than the other way around. So sizeof(int) is probably appropriate but 4 or PROTOCOL_INTEGER_SIZE might be more appropriate still.
The idea is correct, but you have a bug:
reinterpret_cast<char*>(&r + sizeof(int))
Should be:
reinterpret_cast<char*>(&r) + sizeof(int)
or
reinterpret_cast<char*>(&r+1)
These or a memcpy equivalent are OK. Anything else risks alignment issues.
It's common currency to use reinterpret_cast for those purposes but the Standard makes it pretty clear that static_cast via void* is perfectly acceptable. In fact in the case of a type like int then reinterpret_cast<char*>(&r) is defined to have the semantics of static_cast<char*>(static_cast<void*>(&r)). Why not be explicit and use that outright?
If you get into the habit, you have less chance in the future of using a reinterpret_cast which will end up having implementation-defined semantics rather than a static_cast chain which will always have well-defined semantics.
Do note that you're allowed to treat a pointer to a single object as if it were a pointer into an array of one (cf. 5.7/4). This is convenient for obtaining the second pointer.
int r = rand();
boost::array<char, sizeof(int)> send_buf;
auto cast = [](int* p) { return static_cast<char*>(static_cast<void*>(p)); };
std::copy(cast(&r), cast(&r + 1), &send_buf[0]);
Minor bug as pointed out by Michael Anderson
But you could do this:
#include <iostream>
union U
{
int intVal;
char charVal[sizeof(int)];
};
int main()
{
U val;
val.intVal = 6;
std::cout << (int)val.charVal[0] << ":" << (int)val.charVal[1] << ":" << (int)val.charVal[2] << ":" << (int)val.charVal[3] << "\n";
}
Why we can do something like
for(int i = 0; i < destination->imageSize; i=i+3)
{
buffer[2] = destination->imageData[i];
buffer[1] = destination->imageData[i+1];
buffer[0] = destination->imageData[i+2];
buffer+=3;
}
but we can not do
char buffer[destination->imageSize];
And how to such thing?
Sorry - I am quite new to C++...
BTW: my point is to create a function that would return a char with an image. If I'd use mem copy how do I delete returned value?
I have to ask, why do you think they're at all related? If you couldn't index an array by runtime variable, it'd be pretty useless for there to even be arrays. Declaring a variable of a size governed by a runtime variable is entirely different and requires fundamental changes to the way the compiler manages automatic memory.
Which is why you can't do it in C++. This may change, but for now you can't.
If you really need a variable sized array you need to allocate one dynamically. You can do it the hard, f'd up way (char * buff = new char[size]...delete [] buff;), or you can do it the easy, safer way (std::vector<char> buff(size)). Your choice. You can't build it "on the stack" though.
char buffer[destination->imageSize]; declares a variable at compile time. At that time, the value of destination->imageSize is not yet known, which is why it doesn't work.
The expression buffer[2] = destination->imageData[i]; (or rather the buffer[2] thereof) is evaluated at run time.
You cannot return a local array. Everything you return will need to be free'd by someone.
The size of a local array must be constant. Always. This is because there is no special logic around arrays in C++. You can use some object collection of STL.
Hmm. Did you try creating a pointer or reference to destination->imageSize and passing that in for the index instead?
Using std::vector you can achieve what you desire. Your function can be defined something like this:
void readImage(std::vector<char>& imageData, std::string& filename)
{
size_t imageSize = 0;
//read file and load imageSize
imageData.resize(imageSize);
// load image into imageData using such as you in your question
for(int i = 0; i < destination->imageSize; i=i+3)
{
buffer[2] = destination->imageData[i];
buffer[1] = destination->imageData[i+1];
buffer[0] = destination->imageData[i+2];
buffer+=3;
}
}
For further improvements you could return a bool that indicates success or failure.
Regarding the cause of C2466, I don't have the official answer but you can declare char arrays with const variables only like so:
const int imageSize = 4242;
char imageData[imageSize]; // No C2466 error
I need to return a unsigned int* from a function. The code below will compile but will crash at run time on a Windows 64 bit machine. I know I am making a silly mistake somewhere and can someone point it out for me. :p. I also have declared the function in my header, so I know its not that error.
Please note I have censored the variable names and numbers because the problem in which this function resides is not for public release yet.
Function:
unsigned int* convertTime(unsigned int inputInteger, unsigned short inputFrac) {
unsigned int* output = new unsigned int[2];
double messageTimeFraction = double(inputFrac) * 20e-6;
output[1] = unsigned int(inputInteger + 2209032000);
output[2] = unsigned int(messageTimeFraction * 2e32);
return output; // Seconds
}
Implementation:
unsigned int* timeStamp;
timeStamp = convertTime(inputInteger,inputFrac);
Well, for starters you have output[1] and output[2]. Arrays are zero-indexed in c/c++, so these should be: output[0] and output[1].
But, since you're asking about c++... I urge you to use std::vector or std::pair.
(Of course, for readability's sake, you might just want to use a trivial struct with useful field names)
I know I am making a silly mistake
somewhere and can someone point it out
for me
Sure, and it has nothing to do with the Q's subject:
output[2] = unsigned int(inputFrac * 2e32);
The correct entries in output are [0] and [1] -- you're indexing out of bounds. "Undefined behavior" results (such as, the crash you observe).
The indexes in an array of 2 elements are array[0] and array[1], so change it to:
output[0] = unsigned int(inputInteger + 2209032000);
output[1] = unsigned int(inputFrac * 2e32);
use output[0] and output[1], C / C++ arrays are 0 - based
Arrays in C++ are zero based, so the elements of your array of size two are output[0] and output[1]
You also might want to return something that better represents the data you are returning, such as a struct with seconds and fractional_seconds members rather than creating a new array.
It's also somewhat strange what you are doing -- 2209032000 is the number of seconds in 70 years, and the result of multiplying a short by 2e32 will overflow the size of unsigned int.
The more usual way to write functions like this in a C style is to pass in the reference to the variable that will be set.
As a convenience you return the output buffer so that the function can easily be used in an expression.
unsigned int* convertTime(unsigned int* output, unsigned int inputInteger, unsigned short inputFrac) {
double messageTimeFraction = double(inputFrac) * 20e-6;
output[0] = unsigned int(inputInteger + 2209032000);
output[1] = unsigned int(inputFrac * 2e32);
return output; // Seconds
}
// later
unsigned int seconds[2];
unsigned int* pseconds;
pseconds = convertTime(seconds,a,b);
I created a time structure for the various formats and wrote converter functions to handle the conversions. By using structures, I do not have to worry about memory leaks and improved readability. Furthermore the code is now more scalable than using dynamic arrays, as I can add more fields and create new time formats.
struct time{
unsigned int timeInteger;
unsigned int timeFraction;
}time_X, time_Y;
My silly mistake was the typo of zero-based indexing but the bigger mistake was using dynamic array.