Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

MEMSET: how do I use it?

Status
Not open for further replies.

fabien

Technical User
Sep 25, 2001
299
AU
Hi There,

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?

Thanks for your help!

Fabien
 
Fabien,

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.

Mark.
 
Thanks Mark!

When you say "to initialize memory for a variety of purposes." can you please be more specific?

Fabien
 
Fabien,

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.

Code:
struct sigaction {
  void (*sa_handler)(int);
  void (*sa_sigaction)(int, siginfo_t *, void *);
  sigset_t sa_mask;
  int sa_flags;
  void (*sa_restorer)(void);
}
We use
Code:
bzero()
or
Code:
memset()
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
Code:
memset()
or
Code:
bzero()
.

Hope this helps.

Mark.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top