Reputation: 9139
I have such array with size of 24 byte
:
char* arr[3] = {"CERN", "0", "ALK"};
printf("%ld\n", sizeof(arr));
Then I try to clear this array from memory by assigning \0
to each element of array:
for (size_t i = 0; i < sizeof(arr)/ sizeof(char*); ++i) {
arr[i] = '\0';
}
But when I want to check the size of array, it still gives me 24 byte
:
printf("%ld\n", sizeof(arr));
> 24
How to completely clear this array from memory that sizeof(arr)
would give 0
?
Upvotes: 0
Views: 2562
Reputation: 121427
sizeof(arr)
is the size of three char*
. It doesn't change when you set each of the pointers to 0
.
How to completely clear this array from memory that sizeof(arr) would give 0?
There's no way to "clear" an array allocated on automatic storage. You really don't need to "clear" it at all.
Note that you should use %zu
to print a size_t
value, which is what sizeof
operator yields. Using an incorrect format specifier is undefined behaviour.
Upvotes: 3
Reputation:
char* arr[3] = {"CERN", "0", "ALK"};
How to completely clear this array from memory that sizeof(arr) would give 0?
It is a static allocation (either an auto/global variable) . memory assigned for arr cannot be cleared.
note : In this case "CERN", "0", "ALK" are probably stored in read only segment.
Upvotes: 1
Reputation: 206727
How to completely clear this array from memory that
sizeof(arr)
would give0
?
It is not possible given your declaration.
You'll have to come up with a different logic to come up with 0
-- the number of items in arr
that are not NULL.
int my_own_array_size(char* arr[], int numElements)
{
int count = 0;
for ( int i = 0; i < numElements; ++i )
{
if ( arr[i] != NULL )
++count;
}
return count;
}
and then use it as:
int count = my_own_array_size(arr, 3);
Upvotes: 1
Reputation: 544
You may a look at this post since it explains the difference between statically and dynamically allocated memory:
What and where are the stack and heap?
Upvotes: -1
Reputation: 121871
No, no, no. There are several different issues here:
If you want to clear a block of memory, use memset()
If you want to zero out a string, all you need to do is set the FIRST character to null: arr[0] = 0;
The sizeof operator tells you the size of your array.
The strnlen() tells you the length of your string.
Even if you've allocated 3 bytes for your array, the actual length of the string might be 0, 1 or 2.
It can never be "3" ... because you need at least one byte for your terminator.
Upvotes: 1
Reputation: 562
You have assigned zeroes to the array, but that's all. You have not changed (and cannot, since you didn't malloc()
it) the amount of memory allocated to the array, only cleared that data inside it.
Upvotes: 1