0

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 ?

lil
  • 3
  • 3
  • Re “It does not works because `memset` function is applied on pointer and not on data it-self”: Do you mean the `sizeof` operator is applied to `data`, which is the function parameter and is a pointer, rather than being applied to the original array holding the data? The C standard does not provide any way to know the size of an array from a pointer. You must design `my_function` to receive the length of the data in some either way, such as another parameter. If `data` points to a string (a null-terminated sequence of characters), you can get its length with `strlen`. – Eric Postpischil Nov 13 '22 at 11:28

1 Answers1

0

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, it's maximum is the most number of bytes you can allocate to an array.