Is it possible to free() or shorten an char array?
You can define a function that helps to calculate the new length of your intended array. This function would basically count the number of trailing bytes that are equal to '\0'
.
unsigned trimmedlen (unsigned char arr[], unsigned arrlen) {
unsigned newlen = arrlen;
for (i = 0; i < arrlen; ++i) {
if (arr[arrlen - i - 1] != '\0') break;
--newlen;
}
return newlen;
}
Now, you can create your new array using VLA (assuming your compiler supports it).
unsigned char newarr[trimmedlen(arr, sizeof(arr))];
memcpy(newarr, arr, sizeof(newarr));
Is it possible to free() a non dynamically memory?
You should not pass an address not returned by malloc
or related routines to free
. The behavior of free
is specified in C 2018 7.22.3.3. Paragraph 2 says:
The
free
function causes the space pointed to byptr
to be deallocated, that is, made available for further allocation. Ifptr
is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call tofree
orrealloc
, the behavior is undefined.