• 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

    • Lol "media control center", these are just the GLOBAL MEDIA CONTROLS directly taken from Chromium without changing anything, why the hell doesn't Microsoft call them by their correct name?
    • vPro is the hardware that a number of software packages use. A lot of the first party management tools from Dell, HP, and Lenovo use vPro. Having said all that, it is kind of a nothing burger. Promised a lot, but doesn't really do much for most people.
    • How about an AI generated weekly wrap-up of all AI news. I skim over articles about which AI claims to have a bigger 'brains' this week (or even today), and it changes too often to even consider it worth remembering.
    • Or…because it makes it obvious what they are referring to. Imagine if Microsoft called it Visual Studio 22.
    • Ghost Downloader 3 v3.5.13 by Razvan Serea Ghost Downloader 3 is a high-performance download manager for Windows, featuring AI-enhanced acceleration, intelligent multi-threading, and smart file segmentation. It supports download resumption via .ghd files, global speed limits, and clipboard monitoring for quick link capture. The interface is built with Fluent Design, offering a modern and smooth user experience. Users benefit from advanced features like sparse file support, system tray integration, proxy configuration, secure SSL options, and automatic filename recognition. Ghost Downloader 3 is ideal for users seeking speed, efficiency, and customization. Core Download Features AI-Powered Acceleration: Experimental feature that dynamically increases thread count (up to 253) to maximize bandwidth usage. Intelligent Segmentation: Divides downloads into multiple parts for parallel processing, supporting breakpoint resume via .ghd files. Dynamic Thread Allocation: Automatically splits faster segments to create new threads, enhancing download speeds. Network & Proxy Support Global Speed Limiting: Allows setting a maximum download speed to manage bandwidth usage. Proxy Support: Compatible with SOCKS5, HTTP, and HTTPS proxies, including auto-detection features. SSL Certificate Verification: Optional SSL verification for secure downloads. System Proxy Detection: Automatically detects system proxy settings across Windows, Linux, and macOS. Windows-Specific Features Fluent Design UI: Modern interface with support for Mica, Acrylic, and Aero background effects. Toast Notifications: Supports Windows 10 (1709+) native notifications. Window Border Accent Colors: Enhanced visual integration with Windows 11. Application Features Smart Filename Recognition: Automatically identifies and decodes filenames from HTTP headers, URL parameters, or paths. Sparse File Support: Utilizes sparse file technology on supported file systems (e.g., NTFS) for efficient disk space allocation. Clipboard Monitoring: Optionally monitors clipboard for download links to facilitate quick task additions. Drag-and-Drop and Paste-to-Add: Supports intuitive methods for adding download tasks. Task Management: Features batch addition, per-task thread customization, pause/resume/cancel options, and hash verification (MD5, SHA1, SHA256). System Integration System Tray Support: Minimizes to system tray with background download capabilities. Automatic Startup and Task Resumption: Configurable to launch on system startup and resume unfinished downloads. Single Instance Enforcement: Prevents multiple instances from running simultaneously. Automatic Update Checks: Optionally checks for new versions on startup. Ghost Downloader 3 v3.5.13 changelog: Improved shared memory handling for macOS ARM by @cy920820 in #176 Fixed empty thread creation bug by @Alpha-Qian in #184 Optimized automatic speed boost feature by @Alpha-Qian in #183 Optimized download engine code by @XiaoYouChR Notes: Ghost Downloader may trigger a warning or show a hit on VirusTotal, but if only a few antivirus engines flag it, it’s likely a false positive. The app is open source, so you can inspect the code yourself for peace of mind. If you want to use Ghost-Downloader-3 on Windows 7, please download the version v3.5.8-Portable. Download: Ghost Downloader 64-bit | Portable 64-bit | ~50.0 MB (Open Source) Download: Ghost Downloader ARM64 | Portable ARM64 Links: Ghost Downloader Home Page | MacOS / Linux | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      abortretryfail earned a badge
      Week One Done
    • First Post
      Mr bot earned a badge
      First Post
    • First Post
      Bkl211 earned a badge
      First Post
    • One Year In
      Mido gaber earned a badge
      One Year In
    • One Year In
      Vladimir Migunov earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      495
    2. 2
      +FloatingFatMan
      255
    3. 3
      snowy owl
      250
    4. 4
      ATLien_0
      228
    5. 5
      +Edouard
      191
  • Tell a friend

    Love Neowin? Tell a friend!