cpointersmemorybuffer

Zero-out data pointed by char pointer


I am trying to zero-out the data pointed by a char pointer like :

int my_function(char *data) {

    // something here...

    memset(data, 0, sizeof(data));

    //...
}

It does not works because memset function is applied on pointer and not on data it-self.

How can I call memset function on data it-self into the memory ?


Solution

  • sizeof(data) returns the size in bytes of the type of the object data, a char* in this case, i.e. it returns exactly how many bytes it takes to store a character pointer but not the actual character array. The char* type does not store the size of the character array to which it points, you must store that size separately in an size_t (see 1).

    void* memset( void* str, int ch, size_t n);

    n is the number of bytes starting from the location str that will all be set to the value ch. The size in bytes of an array of type T having n elements is returned (in a size_t) by sizeof(T[n]).

    1: size_t behaves exactly as an unsigned int but may have different numerical capacity, its maximum is the largest size (in bytes) of array that is possible or allowed on the target system.