• 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

    • The list of Mac devices rumored to get macOS 26 by Hamid Ganji Apple will announce macOS 26 or macOS Tahoe at its Monday Worldwide Developers Conference. As has been reported multiple times over the past weeks, all Apple operating systems will receive a UI overhaul, a touch of AI, and new names at this year's WWDC. The logic behind the "26" in the new macOS version is that Apple aims to align its naming schedule with its 2025-2026 release cycle. The same version number will also appear across iOS, iPadOS, watchOS, and tvOS. While skipping multiple software versions raises many questions, it might help maintain consistency in the Apple ecosystem. With just two days away from the WWDC kick-off, many Mac owners might wonder if the upcoming macOS 26 is compatible with their devices. Here's the rumored list of compatible Mac devices with the macOS 26: MacBook Air (M1 and later) MacBook Pro (2019 and later) iMac (2020 and later) Mac Mini (M1 and later) Mac Studio (all models) Mac Pro (2019 and later) This report comes from MacRumors, which cites a private account on X as the source. However, the interesting thing about this list is that, according to the leaker, Apple might end software support for the MacBook Pro 13-inch (2020 model, two Thunderbolt 3 ports). For now, we should take this claim with a pinch of salt. The 2020 MacBook Pro 13-inch launched with both Intel and Apple Silicon M1 processors. It also comes with two port configurations. Apple is expected to end support for more Intel-based Mac devices this year, and this specific MacBook Pro variant might also be on Apple's kill list. WWDC 2025 kicks off on June 9, and Apple will unveil the latest version of its operating systems with an overhauled UI and a slew of AI-related features. So far, we know what Apple Watch models might get watchOS 26. Apple will announce the compatibility list of various devices at Monday's event.
    • It's a separate question to the thread, but I have VLC and qBitorrent working on W11 without any issue. Download->install->job done.
    • Currently I am using Display Port connection to monitor.   If I change the setting you show above it does make text larger, but ALL text larger not just icon text on desktop. Also is doesn't change the text weight at all. That setting leaves it very thing test. I want bold, or semibold.
    • Patch My PC - Home Updater 5.2.3.0 by Razvan Serea Patch My PC Free is a reliable tool which can quickly check your PC for outdated software. The supported third-party programs include a large number of widely-used applications, including Adobe Reader, Mozilla Firefox, Java, 7-Zip, BleachBit, Google Chrome and many more. Patch My PC Home updater features: Updates over 500 common apps check including portable apps Ability to cache updates for use on multiple machines No bloatware during installations Applications install/update silently by default no install wizard needed Optionally, disable silent install to perform a manual custom install Easy to use user interface Change updated and outdated apps color for color blindness Option to automatically kill programs before updating it Create a baseline of applications if installing on new PC’s Quickly uninstall multiple programs Scan time is usually less than 1 second Set updates to happen on a schedule Skip updates for any application you don’t want to update Suppresses restarts when performing application updates Patch My PC - Home Updater 5.2.3.0 changelog: Startup Manager New tab to manage which apps launch at startup. This helps speed up your boot time and gives you control over what runs in the background. Generate Diagnostic ZIP You can now create a diagnostic ZIP file from the About page. This helps if you need to send logs on our support forum for Home Updater. Remove Portable Apps Right-click any portable app in the App Catalog or Uninstaller page to remove it directly. Applications Added FFmpeg (Full Shared) – Portable Fing G-Helper – Portable IntelliJ IDEA Community Edition K-Lite Basic Codec Pack K-Lite Full Codec Pack K-Lite Standard Codec Pack KeePass Password Safe v1 LibreOffice Help Pack MemTest86 – Portable Nexus Vortex Nvidia Profile Inspector – Portable Pale Moon – Portable ViVeTool – Portable WinCDEmu Windows PC Health Check Wise Video Converter Applications Removed Driver Easy Download: Patch My PC 5.2.3.0 | 54.8 MB (Freeware) Download: Patch My PC Portable | 31.0 MB (Portable) View: Patch My PC Free Homepage | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • "For starters, Microsoft Edge is getting a media control center. This feature is intended to let you control multiple media sources from any website in a single place." Oh, I've got this Media Control and couldn't find how to disable it. I hate it when a button appears on a toolbar where there was none just before I press Play. I probably would find it at least somewhat useful if I could start playing media from any opened tab, but now it only shows controls for media I've already started playing. If anyone knows how to disable it - I'd appreciate a hint.
  • 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
      491
    2. 2
      +FloatingFatMan
      258
    3. 3
      snowy owl
      249
    4. 4
      ATLien_0
      223
    5. 5
      +Edouard
      190
  • Tell a friend

    Love Neowin? Tell a friend!