Home > Mobile >  How to clear uninitialized memory in C ?
How to clear uninitialized memory in C ?

Time:03-05

I have an incoming unitialized string. I want to remove all the uninitialized memory characters after "Keep" (Keep췍췍췍췍췍췍). Here is my code:

#include <windows.h>
#include <conio.h>

int main()
{
WCHAR* sNew = new WCHAR[10];
sNew[0] = 'K';
sNew[1] = 'e';
sNew[2] = 'e';
sNew[3] = 'p';

_getch();
}

How do I achieve this? In this example, I know the length I want to keep is the first four elements of the array, BUT, I need to code it for varying lengths.

I read that the '췍' symbol is the default for Visual Studio in Debug mode, so in release mode it could be

CodePudding user response:

Practically, I'd suggest a few things

  • don't use C-style arrays like this and prefer the string type, letting the compiler optimize it (const for fixed strings)
    std::string const foo = "bar";
    
  • generally don't manufacture uninitialized memory where possible (for example, consider a vector which will manage the allocation state for you)

CodePudding user response:

You can zero out the entire memory with memset:

WCHAR* sNew = new WCHAR[10];
memset(sNew, 0, 10*sizeof(WCHAR));

If you're using this memory as a c-string, then you really just need to terminate the string with a null character.

WCHAR* sNew = new WCHAR[10];
sNew[0] = 'K';
sNew[1] = 'e';
sNew[2] = 'e';
sNew[3] = 'p';
sNew[4] = '\0';

CodePudding user response:

You can initialize all members of the array like this:

#include <windows.h>
#include <conio.h>

int main()
{
    WCHAR* sNew = new WCHAR[10]{0};  // Set all members to zero.

    WCHAR  aNew[10]{0};              // Set all members to zero.

}

CodePudding user response:

Method 1

You can use std::fill as shown below:

WCHAR* sNew = new WCHAR[10];
std::fill(sNew, sNew   10, 'a'); //i have used `a` as an example you can chose some other character according to your needs/preference

Or if you want to set characters after Keep in your example you could do:

WCHAR* sNew = new WCHAR[10];
sNew[0] = 'K';
sNew[1] = 'e';
sNew[2] = 'e';
sNew[3] = 'p';

std::fill(sNew   4, sNew   10, 'a'); //note the   4 used here

Method 2

Also do note that you can value initialize all the elements of the array as shown below:

WCHAR* sNew = new WCHAR[10](); //note the empty pair of parenthesis
  • Related