5

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.

10
  • 1
    why bother with cleaning the value if you want to update the contents of s anyway? Commented Nov 19, 2012 at 12:43
  • 5
    sizeof(2*5) looks funny... Try also sizeof(2/0) Commented Nov 19, 2012 at 12:43
  • 3
    @AlexFarber that would give you a block of infinite size. Commented Nov 19, 2012 at 12:44
  • 3
    @WouterH A dream comes true! You deserve a Nobel prize ;) Commented Nov 19, 2012 at 12:44
  • 5
    @WouterH: and sizeof(-1000) would give you a negative-sized array: quite useful if you are out of memory! Commented Nov 19, 2012 at 12:45

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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); 

Comments

4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.