Erasing a Char

Okay i am working on someone elses code. They do alot of this:

char description[256];
description[0]=0;

I know this would put a \0 in the first spot of the character array. But is this even a safe way to erase a string?

Also visual studio keeps reporting memory leaks, and i've pretty much tied this done to the strings that are used.

Ps. Yes i know about std::string, yes i use that. This isn't my code.

Answers


To initialize the string to 0, you could do:

char description[256] = {0};

that will assign 0 to every element of the array.

Just setting the first element to 0 ('\0') does not erase it's contents. It doesn't even guarantee the entire string is set to the null character.

As stated by others, you can't "erase" statically-created objects until the function closes, when it gets abandoned. Technically, it's not erased when the function is abandoned either - the stack pointer is merely changed. If you're paranoid about the data being erased, you should iterate through the array, setting each entry to 0 ('\0').


Setting the first element of the char array to \0 is enough to ensure that 'description' is a properly formatted, actual string. Elements 1 thru 255 can all be garbage, so long as element 0 is 0, description is a zero-length string.

You dont have to worry about memory leaks in the code posted above, because the array is allocated on the stack. Once it falls off the stack (goes out of scope), the char array is deallocated.


Need Your Help

How to enable a button that is disabled based on textBox? c#

c# winforms button

I got a textBox that load value from my database and a button that update changes based on the value of the textBox. What I need is to enabled the button if the textBox value changed. For example, ...

Default implementations of Abstract methods

delphi oop abstract-methods

I am dealing with a large codebase that has a lot of classes and a lot of abstract methods on these classes. I am interested in peoples opinions about what I should do in the following situation....

How to draw a bezier curve with variable thickness on an HTML canvas?

javascript html5-canvas bezier

I want to make a visualization with bezier curves connecting boxes. More important edges should be thicker. Every box has one output but many inputs. Therefore, I want to keep the thickness of the

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.