CNNTT
CNNTT

Reputation: 27

How to delete the data of a pointer in C?

char *p = (char *) malloc(10 * sizeof(char));

... let p point to some chars

free(p);
char *p = (char *) malloc(10 * sizeof(char));

Since freeing p doesn't delete the data stored at the particular memory address I'm facing the problem that for large pointers the newly allocated memory overlaps with the old one what is obviously problematic. How can I delete the data to which a pointer points to ?

Upvotes: 0

Views: 3672

Answers (3)

Willis Blackburn
Willis Blackburn

Reputation: 8204

You can't assume that memory returned from malloc is initialized to anything. It may be initialized to zero the first time, but you can't rely on that behavior.

You can call memset to clear the memory returned from malloc. Or consider using calloc, which zeros out the memory before returning the pointer to you.

In general programs only use memset or calloc if they really need the memory buffer to be initialized to zero. If you're just going to copy a string into it, you don't need to initialize it to zero first; you can just copy the string and (if necessary) append a '\0' to the end.

Upvotes: 2

0___________
0___________

Reputation: 67476

void myfree(void *ptr, size_t size)
{
    volatile char *ucptr = ptr;
    if(ucptr) while(size--) *ucptr++ = 0;
    asm("");
    free(ptr);
}

char *p = (char *) malloc(10 * sizeof(*p));

//... let p point to some chars

myfree(p, 10 * sizeof(*p));
char *p = (char *) malloc(10 * sizeof(char));

Upvotes: -1

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13171

There's no such concept as "deleting" data in C. When you allocate some memory for data, there will always be data there. It will probably start as garbage until you put your data there, and your data will stay there until you put something else there. You could replace your data with something like 0s or 0xFFs with memset(), which would overwrite your data. You must do so /before/ free()ing it.

Upvotes: 1

Related Questions