• 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

    • Thank you for mentioning Windows Vista in the title of a news article!
    • Let's be real. Part of the motivation of the UI change is to increase CPU/RAM usage, which slows down older devices and makes battery life worse, therefore tempting people into upgrading to the latest devices. We've been through this enough times to know that the iOS updates never improve performance. Personally I value battery life over eye candy.
    • Apple announces watchOS 26 with a 'Workout Buddy,' new gestures, and more by Taras Buria Apple has unveiled watchOS 26, another operating system under the new naming scheme (all of Apple's systems now feature the same version number to match the current/upcoming year) and "Liquid Glass" Redesign. The latter is a dynamic interface that features translucency, reflections, parallax, and other visual candy. Aside from the redesign and a new number, Apple is introducing new health and workout features. Workout Buddy is a feature that offers personalized, spoken motivation during workouts. It analyzes your pace, heart rate, and fitness history, delivering real-time encouragement and more engagement, like having someone else work out next to you, providing useful information and cheering you up. Here is an example of what you will hear with Workout Buddy: The Workout app also has a more streamlined interface with four buttons in the corners for quick access to favorite features during workouts. You can set up music and podcasts right in the Workout app so that your favorite content starts playing when you begin your workout. In addition, Apple announced a new one-handed wrist flick gesture that allows users to dismiss notifications with a quick flick, which is convenient when you cannot use your both hands to interact with your watch. Other changes include the Notes app, which now lets you access notes on the Apple Watch, Hold Assist and Call Screening in the Phone app, Live Listen with real-time Live Captions of what the iPhone hears, improvements to the Photos face, and more. watchOS 26 will be available later this year, and the first developer betas are expected soon.
    • tvOS 26 arrives with karaoke mode, updated profile switcher, Liquid Glass, and more by Aditya Tiwari WWDC 2025 is now live, and Apple has finally renamed all of its operating systems to version 26. This year, we have tvOS 26 for the Apple TV, featuring the freshly-baked Liquid Glass software design. Apple explained that Liquid Glass brings a fresh and vibrant look to Apple TV, "delivering a fresh and expressive design that beautifully reflects and refracts its surroundings using real-time rendering." Content is the primary focus of the experience when you fast-forward, rewind, or change a setting from the Control Center. The redesigned Apple TV app now features new poster art for movies and TV shows, with a touch of Liquid Glass. Users can now choose whether to display the profile switcher UI when their Apple TV wakes up, allowing them to quickly access their Watchlist and recommendations in the TV app, as well as playlists in Apple Music. Speaking of Apple Music, your iPhone can now double as a handheld microphone for Apple TV. The new karaoke mode allows multiple users to queue up songs from their iPhones and sing along, with support for lyrics translation and pronunciation. Apple has updated the FaceTime experience to make it consistent with iPhone. Contact Posters introduced with iOS 17 are now available on Apple TV, which display a contact's customized photo and name when starting a FaceTime call. Live Captions support on FaceTime now includes French, German, Japanese, Korean, Mandarin, and Spanish. FaceTime on Apple TV has been updated to display phone and voice call notifications for active profiles. Users can use their connected HomePod speakers or iPhone to answer them. Apart from that, tvOS 26 also brings new Aerial screen savers, featuring India's Goa and Kerala. Users can also personalize their screensaver experience and designate any AirPlay-enabled speaker as the permanent speaker for Apple TV. tvOS 26 has also made the sign-in experience a bit easier for users. Developers can link app logins to an Apple account, making it quicker for users to access their apps and content when setting up a new device. The new tvOS update is now available for testing through the Apple Developer Program, supported on Apple TV 4K (2nd generation and later). Meanwhile, the updated sing-along feature is available on iPhone 11 and later with Apple TV 4K (3rd generation).
  • Recent Achievements

    • Rookie
      CHUNWEI went up a rank
      Rookie
    • Enthusiast
      the420kid went up a rank
      Enthusiast
    • Conversation Starter
      NeoToad777 earned a badge
      Conversation Starter
    • Week One Done
      VicByrd earned a badge
      Week One Done
    • Reacting Well
      NeoToad777 earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      479
    2. 2
      +FloatingFatMan
      276
    3. 3
      ATLien_0
      257
    4. 4
      Edouard
      205
    5. 5
      snowy owl
      200
  • Tell a friend

    Love Neowin? Tell a friend!