• 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

    • As it would on any other tech website whether it be Windows, Apple, etc. I wouldn’t expect it any other way.
    • Mozilla should shut down everything except the browser and the services they whitelabel (for example Firefox VPN from Mullvad). Everything else just cost them money and have never returned any revenue. Focusing in the browser is what makes sense considering what is going to change regarding their income sources. About Firefox and chromium... if they ever have to abandon Gecko because of financial issues it is more likely to use Apple's WebKit and not Chromium and Blink. WebKit is more versatile for Firefox because it will allow them even to keep Firefox's extension ecosystem. The same way GNOME Web which is a WebKit browser has experimental Firefox extension support.
    • I really dont like how they’ve put shadows under window elements making the sidebar and toolbar buttons look like they sit above the window itself. Looks very odd and clunky.
    • Rubbish. It's chock-full of ads and with manifest 3.0,the gloves are off. Google does not even pretend now. They want évil and want your data
    • Glary Utilities 6.27.0.31 by Razvan Serea Glary Utilities offers numerous powerful and easy-to-use system tools and utilities to fix, speed up, maintain and protect your PC. Glary Utilities allow you to clean common system junk files, as well as invalid registry entries and Internet traces. You can manage and delete browser add-ons, analyze disk space usage and find duplicate files. You can also view and manage installed shell extensions, encrypt your files from unauthorized access and use, split large files into smaller manageable files and then rejoin them. Furthermore, Glary Utilities includes the options to find, fix, or remove broken Windows shortcuts, manage the programs that start at Windows startup and uninstall software. All Glary Utilities tools can be accessed through an eye-pleasing and totally simplistic interface. Glary Utilities 6.27.0.31 changelog: Optimized Disk Cleaner: Optimized the scanning algorithm for Firefox to enhance user experience. Optimized Disk Cleaner: Added support for Nitro Pro 14. Optimized Tracks Eraser: Optimized the scanning algorithm for Firefox to enhance user experience. Optimized Tracks Eraser: Added support for Nitro Pro 14. Optimized Startup Manager: Optimized the review algorithm to enhance user experience. Optimized Uninstaller Manager: Optimized the scanning algorithm to enhance user experience. Minor GUI improvements. Minor bug fixes. Download: Glary Utilities 6.27.0.31 | 27.0 MB (Freeware) Download: Portable Glary Utilities | 32.3 MB View: Glary Utilities Homepage | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • One Month Later
      Æhund earned a badge
      One Month Later
    • One Month Later
      CoolRaoul earned a badge
      One Month Later
    • First Post
      Kurotama earned a badge
      First Post
    • Collaborator
      Carltonbar earned a badge
      Collaborator
    • Explorer
      MusicLover2112 went up a rank
      Explorer
  • Popular Contributors

    1. 1
      +primortal
      508
    2. 2
      ATLien_0
      269
    3. 3
      +FloatingFatMan
      241
    4. 4
      +Edouard
      202
    5. 5
      snowy owl
      168
  • Tell a friend

    Love Neowin? Tell a friend!