gizgok
gizgok

Reputation: 7649

How to clear memory contents in C?

I'm defining a char pointer in this manner.

char *s=(char *)malloc(10);

After I fill in all possible values that can fit here, I want to clear whatever I wrote to s and without using malloc again want to write in s? How can I do this?

I need to update the contents but if in the last iteration not all values are updated, then I'll be processing over old values which I do not want to do.

Upvotes: 5

Views: 75139

Answers (3)

Olaf Dietsche
Olaf Dietsche

Reputation: 74128

Be careful!

malloc(sizeof(2*5)) is the same as malloc(sizeof(int)) and allocates just 4 bytes on a 32 bit system. If you want to allocate 10 bytes use malloc(2 * 5).


You can clear the memory allocated by malloc() with memset(s, 0, 10) or memset(s, 0, sizeof(int)), just in case this was really what you intended.

See man memset.


Another way to clear the memory is using calloc instead of malloc. This allocates the memory as malloc does, but sets the memory to zero as well.

Upvotes: 12

Jason
Jason

Reputation: 32538

You can "clear" memory by using memset, and setting all the bytes in the memory block to 0. So for instance:

#define MEMORY_BLOCK 10

//allocate memory
unsigned char* s = malloc(MEMORY_BLOCK);

//... do stuff

//clear memory
memset(s, 0, MEMORY_BLOCK);

Upvotes: 5

unwind
unwind

Reputation: 400159

A couple of observations:

  • You don't need to cast the return value of malloc() in C.
  • Your malloc() argument looks wrong; note that sizeof is an operator, not a function. It will evaluate to the size of the type of its argument: 2 * 5 has type int, so the value will probably be 4. Note that this is the same for all integer expressions: sizeof 1 is the same as sizeof 100000000.

Your question is very unclear, it's not easy to understand why you feel you have to "clear" the string area. Memory is memory, it will hold what you last wrote to it, there's no need to "clear" it between writes. In fact, a "clear" is just a write of some specific value.

Upvotes: 4

Related Questions