• 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

    • New Outlook for Windows landing in Microsoft 365 Education accounts next January by Paul Hill Microsoft has announced that from January 2026, Microsoft 365 Education users will be able to switch to a “modern, AI-powered” Outlook for Windows. The Redmond giant said that a new toggle will show up for eligible users that will let them decide whether to run classic Outlook or the new Outlook for Windows. The new version, Microsoft said, brings numerous improvements including more streamlined communication, features to boost your productivity, and more ways to personalize your experience. As this update is coming to Microsoft 365 Education accounts, it means it’ll affect both students and teachers. The refreshed interface more deeply integrates with Microsoft 365 Copilot to deliver: smarter email and calendar management with features such as Pinning and Snoozing; personalized themes that match your style and preferences; and Copilot-powered assistance to help you draft, summarize, and organize your emails and appointments. Microsoft is obviously keen for users to switch over to the new interface when it's available to foist AI on you. However, if you are reticent about using these AI tools, you can always revert back to the classic Outlook for Windows, at least for a while after the new version is released. The new toggle will begin rolling out globally next January. Before then, Microsoft 365 Education users will get in-app notifications ahead of the change to prepare them, and educational organizations will have the power to opt out or manage the experience through administrator settings. While most Microsoft 365 Education users will get the toggle, there are some exceptions. These include: organizations that have opted out of automatic migration; users with perpetual licenses; on-premises account holders; and devices where the toggle is hidden via policy. The upcoming changes will not require any administrative action during the rollout. Microsoft says administrators, if they want to, can notify users about the upcoming change; update their internal documentation; and review the documentation for Admin control over migration. The firm said that after the rollout, policy controls will become available through Group Policy Objects (GPO), Cloud Policy, and Intune. In terms of compatibility with other platforms, the new Outlook for Windows will be compatible, including with Mac. Users will still be able to access their accounts normally through the Outlook app available for macOS or via the Outlook web app.
    • Might be a joke to a shortsighted person, but that's the minimum for ANY EV to be as reliable and hassle-free as my '12 Highlander Hybrid. Sure my Hybrid gets even less at 372mi (in the winter) - 455mi (in the summer) on a tank, but at least I can refill it for another 372mi-455mi in merely 10 minutes or less without ANY of the following worries: Without all of that peace of mind, an EV will require 800mi/charge to give similar peace of mind for me. I ain't buying and worrying about separate vehicles just for city commuting and long road trips. That's a total waste of cash IMO. My Highlander Hybrid perfectly suits both use cases, and for any EV to be worth my consideration, they'll have to suit them too. Maybe for you that solely resides in 1 city and never travel by road it makes no sense, but for anyone with experience of traveling across cities here in Canada, it makes total sense given the long distances. I ain't suddenly adding another 1hr to my road trip just for EVs, mere coffee and snacks suffice for my trips (~800km), and those certainly don't take me 1hr.
    • Microsoft will reportedly hit Xbox division with a massive wave of layoffs soon by Pulasthi Ariyasinghe It was only a few days ago that a report came out regarding a mass layoff wave at Microsoft. While that report only mentioned sales staff that were to be affected, now, another report has landed that mentions the company's Xbox gaming division being another layoff target. According to Bloomberg's Jason Schreier, Microsoft has another major round of layoffs planned for the Xbox division as it reorganizes the company ahead of the new fiscal year. This unfortunate news for many staff will be announced as soon as next week, per the report Bloomberg has gained the information from sources that had asked not to be named, who had said that managers inside Xbox are already expecting the job cuts to take effect soon. While no specific developers, divisions, or numbers were mentioned, "substantial cuts" are reportedly incoming as a part of this change. The gaming division of Microsoft has gone through multiple layoff waves in recent years. Late 2024 saw 650 jobs being cut from Xbox corporate and supporting teams. Earlier in the same year, over 1,900 staff from Activision Blizzard, ZeniMax, and Xbox development teams were let go from Microsoft. Microsoft has released a number of high-profile first games as of late, including Doom: The Dark Ages, Avowed, and Indiana Jones and the Great Circle, and is also pursuing a multi-platform strategy that has Xbox games releasing on PlayStation platforms. It has also confirmed next-gen Xbox hardware is now in development and recently unveiled a first-ever official Xbox handheld initiative. If the latest report turns out to be accurate, we should have an official announcement sometime next week. Microsoft's current fiscal year is slated to end on June 30.
  • Recent Achievements

    • Week One Done
      Sharon dixon earned a badge
      Week One Done
    • Dedicated
      Parallax Abstraction earned a badge
      Dedicated
    • First Post
      956400 earned a badge
      First Post
    • Week One Done
      davidfegan earned a badge
      Week One Done
    • First Post
      Ainajohn earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      593
    2. 2
      ATLien_0
      223
    3. 3
      Michael Scrip
      170
    4. 4
      +FloatingFatMan
      152
    5. 5
      Som
      135
  • Tell a friend

    Love Neowin? Tell a friend!