Will this code leaks memory

L

LinuxGuy

Can someone please tell if following code leaks memory

void someFunction()
{

char MyArray[512];

memset(MyArray,0,512);

}
 
D

Dervish

No - it can't leak. However it is better to write
memset(MyArray,0,sizeof(MyArray));
to avoid duplicating of magic number (512).
 
A

Alf P. Steinbach

* Dervish:
> [non-quoting]

Please read the FAQ and the monthly welcome message.

Please quote what you're replying to.

This isn't a web forum or instant messaging.

No - it can't leak. However it is better to write
memset(MyArray,0,sizeof(MyArray));
to avoid duplicating of magic number (512).

memset is not type safe and thus should be avoided where practically
possible.

In this case, if a raw array is really needed (it seldom is), write

void someFunction()
{
char MyArray[512] = {};
}
 
L

LinuxGuy

even if I don't use memset() and just declare the array then will it be
deallocated when function exits..
 
M

mlimber

LinuxGuy said:
even if I don't use memset() and just declare the array then will it be
deallocated when function exits..

First, to reiterate: please QUOTE what you are replying to. Not
everyone is using Google Groups, and it helps all to follow the
conversation. (To quote automatically from GG, click "show options" and
then "reply" in the revealed header.)

Second, you seem to have either asked a question but omitted to proper
punctuation or inappropriately phrased an indicative sentence as an
interrogative. In either case, the answer is that, yes, automatic
variables and arrays are freed when they leave scope.

Cheers! --M
 
C

Christopher Benson-Manica

LinuxGuy said:
even if I don't use memset() and just declare the array then will it be
deallocated when function exits..

Your failure to post properly has already been duly noted.

In answer to your actual question, yes, your array will be deallocated
when the function exits, no matter what you do to it. If your
implementation uses a stack (it probably does), it may help to know
that space allocated on the stack is *always* freed when the function
returns. Such is the beauty of "automatic" (whatever C++ calls it)
storage.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

memory manager to prevent memory leaks 4
Memory leaks 2
memory leaks 26
pthread memory leaks 15
Debugging memory leaks 20
Converting an Array to a String in JavaScript 7
What code is this 2
memory leaks - tools and docs 0

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top