I am having problem determining in what situation(s) memset should be used. I know I can use it to delete an array and it is faster than looping through the array. Should I use "delete" instead?
memset() writes memory that has been allocated. It is sometimes used to initialize memory for a variety of purposes. It is sometimes used to clear a structure which is passed by reference for the purposes of returning data to the caller (for example, see shmctl(), semctl(), etc).
delete frees memory which has been allocated with new. You should not use delete to initialize memory.
Probably the best example that I can think of is sigaction in UNIX. A sigaction is a structure which refernces actions to tasks when a signal is raised. The fields of this structure specify various actions to take, depending on which of them are non-zero. In linux the structure look like this.
to initialize this structure to zero before we choose our desired action.
We then make a call to
Code:
sigaction()
to specify our desired behavior.
Unix system calls are loaded with these types of complex function calls.
Other applications of
Code:
memset()
are to initialize memory to look for bugs. Sometimes certain bugs (uninitialized memory bugs) are hard to find because the memory is different every time the program runs. Sometimes a programmer will fill memory with a pattern which he knows will crash a program to catch this type of bug. I have seen wrappers on malloc() which zero all allocated memory automatically using
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.