Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ cout uncasted memory (void)

Tags:

c++

casting

cout

This is the scenario;

// I have created a buffer
void *buffer = operator new(100)

/* later some data from a different buffer is put into the buffer at this pointer
by a function in an external header so I don't know what it's putting in there */

cout << buffer;

I want to print out the data that was put into the buffer at this pointer to see what went in. I would like to just print it out as raw ASCII, I know there will be some non-printable characters in there but I also know some legible text was pushed there.

From what I have read on the Internet cout can't print out uncasted data like a void, as opposed to an int or char. However, the compiler wont let me cast it on the fly using (char) for example. Should I create a seperate variable that casts the value at the pointer then cout that variable, or is there a way I can do this directly to save on another variable?

like image 285
jwbensley Avatar asked Feb 19 '26 00:02

jwbensley


1 Answers

Do something like:

// C++11
std::array<char,100> buf;
// use std::vector<char> for a large or dynamic buffer size

// buf.data() will return a raw pointer suitable for functions
//   expecting a void* or char*
// buf.size() returns the size of the buffer

for (char c : buf)
    std::cout << (isprint(c) ? c : '.');

// C++98
std::vector<char> buf(100);

// The expression `buf.empty() ? NULL : &buf[0]`
//   evaluates to a pointer suitable for functions expecting void* or char*

// The following struct needs to have external linkage
struct print_transform {
    char operator() (char c) { return isprint(c) ? c : '.'; }
};

std::transform(buf.begin(), buf.end(),
               std::ostream_iterator<char>(std::cout, ""),
               print_transform());
like image 186
bames53 Avatar answered Feb 21 '26 13:02

bames53



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!