• 0

C++ Char* buffer sizeof


Question

I am converting some code i wrote in C# to C++.

I have programmed a server which works perfectly fine HOWEVER,

When sending data to the client my:

unsigned short int buffer_size = 1024 *2; // 2mb
char *_buffer = new char[buffer_size]; //Char is prepared to send and recieve up to 2048 characters

The issue is that if the server sends the string:

"Neowin.net is awesome!" //length is 22

 

The char size is equal to the buffer_size which means i would be sending 2mb ever time i want to send, when all i really need is 22 bytes

 

 

FROM MY UNDERSTANDING i can not use:

sizeof(*buffer);

I would like to convert the char* to a string and get the length of the string and multiply it by the sizeof(char) to get the sizeof buffer

__

 

 

How can i convert a char * to a string?

 

 

 

Link to comment
https://www.neowin.net/forum/topic/1230937-c-char-buffer-sizeof/
Share on other sites

3 answers to this question

Recommended Posts

  • 0

What format is the string in the buffer in? Do you know if it is null terminated?
If so you can use strlen to get the length, or just pass the pointer to a std::string (make sure to free the buffer or ideally use std::unique_ptr).

std::unique_ptr<char[]> buffer = std::make_unique<char[]>(buffer_size);
 
// Either
const size_t length = strlen(buffer.get());
 
// Or
std::string str(buffer.get());
 

If the buffer is not null terminated, then you will need to supply the length to std::string yourself.

std::unique_ptr<char[]> buffer = std::make_unique<char[]>(buffer_size);
 
std::string str(buffer.get(), string_length);

You will also need to consider issues involving buffer overflow if the string is larger than your buffer size. There may also be more idiomatic C++ solutions using streams and string instead of raw buffers.

  • 0
  On 27/09/2014 at 11:21, Lant said:

What format is the string in the buffer in? Do you know if it is null terminated?

If so you can use strlen to get the length, or just pass the pointer to a std::string (make sure to free the buffer or ideally use std::unique_ptr).

std::unique_ptr<char[]> buffer = std::make_unique<char[]>(buffer_size);
 
// Either
const size_t length = strlen(buffer.get());
 
// Or
std::string str(buffer.get());
 

If the buffer is not null terminated, then you will need to supply the length to std::string yourself.

std::unique_ptr<char[]> buffer = std::make_unique<char[]>(buffer_size);
 
std::string str(buffer.get(), string_length);

You will also need to consider issues involving buffer overflow if the string is larger than your buffer size. There may also be more idiomatic C++ solutions using streams and string instead of raw buffers.

 

Though this format your provided surly is not recognizable to me (maybe its CLI?) Thank you! this got me on the right track.

I haven't written it yet but what i plan on doing is doing what i was going to from the start. I am going to get the String from the char * array and get the length of the string to multiply it by sizeof(char).

 

Thanks for reassuring my strategy. Do you mind telling me what version of C++ you provided?

  • 0

This is C++11 (well std::unique_ptr is, strlen is a C function available in C++ and std::string will definitely be available to you).

 

Why are you multiplying the length of the string by sizeof(char)? An important difference between C++ and C# is that char in C++ is typically 1 byte and 2 bytes in C#. This is because char is special to C# as it represents a character. In C++ char just represents a piece of memory that is at least 1 byte. So in C++ you have to consider how the string is going to be encoded (ASCII, UTF-8 will be the common two for one byte characters. LE UTF-16 is typical for 2 byte characters and I think is what Java and C# use). There is wchar_t for wide characters and char16_t and char32_t for 2 and 4 byte characters. Essentially strings in C++ get difficult when you want more than ASCII.

But that probably just confused you (it still confuses me and I've had to deal with big applications that mixes latin-1, UTF-8, ANSII and LE UTF-16).

This topic is now closed to further replies.
  • Posts

    • just in time for it to be replaced with something that makes everyone unhappy! - The Microsoft way
    • Is this written by AI? The article contradicts itself and doesn't even line up with the title.
    • Pale Moon 33.7.2 by Razvan Serea Pale Moon is an Open Source, Goanna-based web browser available for Microsoft Windows, Linux and Android, focusing on efficiency and ease of use. Make sure to get the most out of your browser! Pale Moon offers you a browsing experience in a browser completely built from its own, independently developed source that has been forked off from Firefox/Mozilla code, with carefully selected features and optimizations to improve the browsers speed, resource use, stability and user experience, while offering full customization and a growing collection of extensions and themes to make the browser truly your own. Features: Optimized for modern processors Based on proprietary optimized layout engine (Goanna) Safe: forked from mature Mozilla code and regularly updated Secure: Additional security features and security-aware development Supported by our user community, and fully non-profit Familiar, efficient, fully customizable interface Support for full themes: total freedom over any elements design Support for easily-created lightweight themes (skins) Smooth and speedy page drawing and script processing Increased stability: experience fewer browser crashes Support for many Firefox extensions Support for a growing number of Pale Moon exclusive extensions Extensive and growing support for HTML5 and CSS3 Many customization and configuration options Pale Moon 33.7.2 release notes: Addressed PWN2OWN-2025-1 (out of bounds read or write in promise) DiD Addressed PWN2OWN-2025-2 (out of bounds read or write when using the ExtractLinearSum optimization) DiD Fixed potential unexpected behavior in embedded protobuf code. DiD Fixed an issue with potentially uninitialized contrast values when enhanced device contrast values can not be read from the O.S. DiD Fixed potential sanitization issues with devtools' "Copy as curl" feature. It should be noted that we do not currently offer cross-platform "curl" features, so this is another DiD for this release. Download: Pale Moon (64-bit) | Portable 64-bit | ~40.0 MB (Freeware) Download: Pale Moon (32-bit) | Portable 32-bit Links: Pale Moon Homepage | Add-ons | Themes | Extensions | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Another disappointing rumor: iPhone 17 won't get a ProMotion display by Hamid Ganji With the iPad Pro in 2017, Apple introduced a new type of display technology for its devices, dubbed ProMotion. The ProMotion feature enables a variable refresh rate, ranging from 24Hz to 120Hz, and it has a critical role in enhancing display sharpness and responsiveness. With the iPhone 13 Pro and iPhone 13 Pro Max in 2021, the ProMotion feature landed on iPhones, but it has stuck with the Pro variants since then, leaving the standard and Plus versions with a regular Super Retina display. While customers expected to get a ProMotion display on the vanilla iPhone 17, and even some rumors hinted at this possibility, the latest leaks suggest ProMotion remains with the Pro iPhone variants for another generation. According to Chinese leaker Fixed Focus Digital on Weibo, Apple has decided to keep the ProMotion feature exclusive to iPhone 17 Pro and Pro Max, and the rest of the lineup would launch with a “normal 120hz screen”. This Chinese leaker has conflicting reports about Apple’s future products. For now, we should take this claim with a pinch of salt and wait for more confirmation from the Apple supply chain insiders. In September last year, analyst Ross Young said the entire 17 lineup would get the ProMotion feature and the Always-on display (via 9to5mac). Young is also a credible source for Apple-related news, but too many conflicting rumors around upcoming iPhones make us question every claim. The only thing that seems certain so far is that Apple will increase the screen refresh rate on the iPhone 17 and 17 Air to 120Hz, which is a significant increase from the current 60Hz on the iPhone 16 base and Plus variants. Also, by boosting the iPhone 17 and 17 Air refresh rate to 120Hz, Apple is more likely to retain the ProMotion feature for the Pro models in the lineup to differentiate devices better from a marketing standpoint.
    • The article clearly states multiple times that he will DONATE his wealth. There's no mention of any loan, but haters gonna hate. He doesn't need to do this, you know? He could just give all that money to his kids and call it a day.
  • Recent Achievements

    • Week One Done
      Jim Dugan earned a badge
      Week One Done
    • Week One Done
      Adam Todd earned a badge
      Week One Done
    • Contributor
      Ed B went up a rank
      Contributor
    • One Month Later
      moporcho earned a badge
      One Month Later
    • One Month Later
      Parotel earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      211
    2. 2
      snowy owl
      156
    3. 3
      ATLien_0
      134
    4. 4
      Xenon
      119
    5. 5
      +FloatingFatMan
      113
  • Tell a friend

    Love Neowin? Tell a friend!