• 0

[C/C++] What is the quickest/most efficient way to clear an array?


Question

So far I've been using:

memset(myarray, 0, sizeof(myarray));

Most of the time, myarray is just a character array, so I fill it full of null characters. However, is there a better way to do this? (It almost seems this is more suited to clearing structures or objects.)

Should I be using a string function? Or, should I use strlen() instead of sizeof()?

Or, at the very least is memset any more or any less efficient that a standard for loop to clear an array? I ask this because I might want to set myarray to a value other than null within the program.

Thanks in advance!

Edit: And yes, performance is quite important for my application.

10 answers to this question

Recommended Posts

  • 0

The only way to be sure is to try both and compare benchmarks. If these strings are ridiculously huge then memset should always win, because memset is usually optimized (it doesn't do it one byte at a time). It depends on a lot of things like whether the compiler you're using inlines memset or not.

BTW: if these character arrays are strictly null terminated strings, then setting only the first character to null should be enough and much faster.

Edited by Sterling Christensen
  • 0
  XerXis said:
oh forgot: if you need to fill a static array with some value i would use std::fill instead of memset

With gcc's standard library, std::fill reduces to the alternatives he's already considering anyway - either a for loop or memset:

  Quote
* This function fills a range with copies of the same value. For one-byte

* types filling contiguous areas of memory, this becomes an inline call to

* @c memset.

See http://www.cs.brown.edu/~jwicks/libstdc++/...rce.html#l00516

It's probably similar with other compilers like Microsoft's.

  • 0
  Brandon Live said:
Do you explicitly need to zero out the buffer? Or is it enough to simply free it?

surely to free it, it would have to have been malloc/calloc/realloc'd and so would just be a simple point and so his current method using sizeof() wouldn't work

  • 0
  dev said:
if its a char array, why clear it all?

if you're going to be keeping "strings" in it, you'd be add a null terminating character after the string anyway so I normally just set the first byte to null.

Uhh, that doesn't work if you allocated the array on the heap... and it doesn't actually free anything up on the stack, since that entire memory block is still allocated on the stack until it goes out of scope. The only reason to do that is if you have a null-terminated string on the stack that you want to make "empty." It neither frees it nor zeros it out.

  dev said:
surely to free it, it would have to have been malloc/calloc/realloc'd and so would just be a simple point and so his current method using sizeof() wouldn't work

If freeing it is all that you care about...

If it's allocated on the heap, you need to free it using whatever allocator you allocated it with. If you used new, you need to use delete[].

If it's allocated on the stack, it's there until it goes out of scope...

In either case, if you want to explicitly zero it out, that's another matter (since free'ing it doesn't actually reset the bits until somebody else allocated that memory and uses it).

  • 0
  Brandon Live said:
Uhh, that doesn't work if you allocated the array on the heap... and it doesn't actually free anything up on the stack, since that entire memory block is still allocated on the stack until it goes out of scope. The only reason to do that is if you have a null-terminated string on the stack that you want to make "empty." It neither frees it nor zeros it out.

He didn't ask about freeing it, he wants to clear it. He wants the memory allocation there, just not the contents. What i said will work for a null terminated string. When working with a string you'd be using strlen and so setting the first byte to null will make strlen return 0 and be no different to if the whole char array was full of 0s.

  Brandon Live said:
If freeing it is all that you care about...

If it's allocated on the heap, you need to free it using whatever allocator you allocated it with. If you used new, you need to use delete[].

If it's allocated on the stack, it's there until it goes out of scope...

In either case, if you want to explicitly zero it out, that's another matter (since free'ing it doesn't actually reset the bits until somebody else allocated that memory and uses it).

I know that, when you use *alloc to allocate memory on the heap you only get a pointer back which, when used with sizeof(), won't give you how much memory is allocated. Seeing as he is using that method to get the size, it is more likely to be a simple char[] on the stack and so won't be able to free it (if that is even what he wanted, which I don't think it is...)

  • 0
  dev said:
He didn't ask about freeing it, he wants to clear it. He wants the memory allocation there, just not the contents. What i said will work for a null terminated string. When working with a string you'd be using strlen and so setting the first byte to null will make strlen return 0 and be no different to if the whole char array was full of 0s.

But it is different, and that's why I asked about his usage. If he believed there was sensitive data there that he wanted to clear our of memory as soon as possible (encryption keys / passwords, or who knows what else) then he may in fact desire to zero the entire buffer.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • RollBack Rx Pro 12.9 Build 2710971022 by Razvan Serea RollBack Rx is a robust system restore utility that enables home users and IT professionals to easily restore a PC to a time before certain events occurred. In essence, it turns your PC into a Instant Time Machine. Regardless of what happens to your PC your can quickly and easily restore your PC to a previous time. Making it easy to rescue you from any PC disaster - saving time, money and PC trouble. Windows System Restore only restores Windows system files and some program files. In addition, if Windows crashes to a point were Windows itself can not boot up (ie. BSOD*) you would not be able to access your Windows System Restore points. In contrast, the RollBack Rx technology works at the sector level of the hard drive and restores everything! - right down to the last byte of data. It sits below Windows. So even if Windows crashes, there’s a sub-console (mini OS) that boots prior to windows. This allows you to access Rollback Rx and go back to a point in time when your system was working trouble-free. Key Features Go back to any previous point in time within seconds. Go back minutes, hours, days, weeks, or even months to any previous snapshot. Does not affect computer performance, uses minimal system resources. Supports unlimited snapshots. Creates a complete system snapshot without having to restart the system. Reverse any system crash within seconds (even if Windows cannot startup). Back out of any failed program, OS updates, and botched updates. Recover from any malware or virus attack within seconds. Works with VMWare and Virtual Machines, both as a host or within the virtual machine as a client. Supports Multi-boot, Multi OS workstations. Lock snapshots to prevent deletion. Intuitive GUI based snapshot manager. Explore, browse, and retrieve files and folders from any snapshot. Drag and drop them into your active system. Roll backwards as well as forwards to any available system snapshot. Allows users to safely test any software. Fast, 100% complete uninstaller. Retrieve files from a crashed PC, even if Windows cannot boot. Access control – manage levels of multiple user and administrative privileges. Automatically schedule snapshots to be taken on a fixed schedule or upon execution of specific files (ie. setup.exe) as well as manually. 256 bit AES snapshot encryption. Prevent unauthorized data theft in case of a stolen laptop. Group Management and Enterprise Network Administration Control (FREE utility). Comes with Stealth Mode where you can hide the RollBack Rx tray icon and splash screen (seen during bootup) Change the startup hotkey for sub-console access (default is HOME). Built-in snapshot defragmenter which will optimize system resources and recover free space. Option to keep files and folders unchanged when you roll-back. Advanced setup configuration wizard for system administrators which will set deployment options and predefined RollBack Rx settings. Offers detailed program operation logging. Supports all industry-standard deployment options including silent installations and pre-installation configuration. Explore RollBack Rx Pro with a 14-day trial, fully functional on Windows 11, 10, 8, and Windows 7 SP1** (32 and 64-bit). RollBack Rx Pro 12.9 Build 2710971022 changelog: General Add PnpLockdown in shieldm.inf Fix registry exclusion problem in Windows 11 24H2 release Add detailed logging for file filter driver Add detailed logging for Windows update Add time stamp to kernel drivers Change kernel driver and Win32 IRP structure Other small bug fixes / typos reported through tech support Endpoint Manager Add client report dashboard Add sound effect when receiving a EPM message. Keep EPM message history Fix bug that oversized Windows symbol files cannot be downloaded Download: RollBack Rx Pro 12.9 | 61.0 MB (Shareware) View: RollBack Rx Home Page Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Universal Media Server 14.12.1 by Razvan Serea Universal Media Server is a DLNA-compliant UPnP Media Server. UMS was started by SubJunk, an official developer of PMS, in order to ensure greater stability and file-compatibility. The program streams or transcodes many different media formats with little or no configuration. It is powered by MEncoder, FFmpeg, tsMuxeR, AviSynth, MediaInfo and more, which combine to offer support for a wide range of media formats. Because it is written in Java, Universal Media Server supports all major operating systems, with versions for Windows, Linux and Mac OS X. To see a comparison of popular media servers, click here. Universal Media Server 14.12.1 changelog: General Added status page to readme Fixed videos not being marked as fully played (#5373) (thanks, @Fredo1650!) Fixed adding YouTube channels from handle URLs (URLs with @ in them) Fixed handling special characters on Linux (#5100) (thanks, @LaTeteDansLesEtoiles!) Fixed directory browsing crash (#5189) (thanks, @jt-gilkeson!) Fixed FFmpeg on Linux x86_64 and arm64 (#5465) (thanks, @KanjiMonster!) Fixed logspam like "Could not hydrate device or its services from descriptor" (#5292) (thanks, MTOakey!) Fixed broken YouTube video playback Fixed web interface E2E testing on CI using outdated code because of overeager caching Fixed broken video playback when burning subtitles to H.265 via FFmpeg (#5486) Improved logging Translation updates via Crowdin Chinese (Simplified) (59%) (thanks, 無情天!) Dutch (41%) (thanks, Matthias!) Hungarian (86%) (thanks, Zoltán Rózsa!) Japanese (69%) (thanks, Yukihuru!) Download: Universal Media Server 14.12.1 | 203.0 MB (Open Source) Download: Other operating systems View: Universal Media Server Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • You sign your rights to reddit when you write on their platform. Free labour for them to make money. The AI companies should also take advantage of that free labour.
    • Brave 1.79.123 by Razvan Serea Brave Browser is a lightning-fast, secure web browser that stands out from the competition with its focus on privacy, security, and speed. With features like HTTPS Everywhere and built-in tracker blocking, Brave keeps your online activities safe from prying eyes. Brave is one of the safest browsers on the market today. It blocks third-party data storage. It protects from browser fingerprinting. And it does all this by default. Speed - Brave is built on Chromium, the same technology that powers Google Chrome, and is optimized for speed, providing a fast and responsive browsing experience. Brave Browser also features Brave Rewards, a system that rewards users with Basic Attention Tokens (BAT) for viewing opt-in ads. This innovative system provides an alternative revenue model for content creators and a way to support the Brave community. Brave 1.79.123 changelog: Leo Improved citation UI. (#45761) General [Security] Fixed missing DDNS navigation throttle for subframes as reported on HackerOne by newfunction. (#46703) Fixed crash which occurred when clicking on the “View site information” icon in the address bar while having “Don’t allow sites to scroll and zoom shared tabs” enabled. (#46566) Fixed crash which occurred with the “Save autofill” prompt in certain cases. (#45546) Upgraded Chromium to 137.0.7151.104. (#46712) (Changelog for 137.0.7151.104) Download: Brave Browser 64-bit | 1.2 MB (Freeware) Download: Brave Browser 32-bit View: Brave Homepage | Offline Installers | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • A summary of the article shouldn't be an issue in theory, as the information is all based within the document itself. The problem with a lot of AI models is that they are trained off both Wikipedia as a primary source and other secondary websites which have less reliable information. As an encyclopaedia it is no doubt going to have bias in one way or another, all encyclopaedias do. The difference is that there is a process for a lot of this information to be figured out whether or not it is an opinion, or the source of that information, and to be aware of the possible bias in the first place, even your own bias as a reader. The way many people understand languages these days is quite limited, particularly in certain areas of the world. This is obvious in many types of "journalism" where some articles are thinly disguised opinion pieces, Where language is carefully curated to push a point of view despite it looking like fact. This is partly why a lot of the Western world is now so divided.
  • Recent Achievements

    • Apprentice
      Adrian Williams went up a rank
      Apprentice
    • Reacting Well
      BashOrgRu earned a badge
      Reacting Well
    • Collaborator
      CHUNWEI earned a badge
      Collaborator
    • Apprentice
      Cole Multipass went up a rank
      Apprentice
    • Posting Machine
      David Uzondu earned a badge
      Posting Machine
  • Popular Contributors

    1. 1
      +primortal
      519
    2. 2
      ATLien_0
      260
    3. 3
      +Edouard
      191
    4. 4
      +FloatingFatMan
      175
    5. 5
      snowy owl
      133
  • Tell a friend

    Love Neowin? Tell a friend!