Home > Enterprise >  Is it possible to free() or shorten an char array?
Is it possible to free() or shorten an char array?

Time:01-22

Is it possible to free() a non dynamically memory?

I have a char array which has a length of 10. I have 4 unwanted zeroes. Is there a way to trim the last four zeros and shorten the array size? Or is the only way to copy the values to a shorten array

char arr[10]={2,8,2,1,7,1,0,0,0,0}

//NON WORKING CODE! just showing the concept
//The shortArr function dosen't work because i have to pre-declare the size

char * shortArr(char * arr){
 unsigned long len = strlen(arr); 
 static char shortArr[len]; //<--- Variable length array declaration cannot have 'static' storage duration
 memcpy(shortArr, arr, len);
    
 return &shortArr;
};

shortArr();

basically what i am doing

unsigned char arr[10]={2,8,2,1,7,1,0,0,0,0}
unsigned char shortArr[strlen(arr)]; 
/*creating a size of 6 by removing the las 0,0,0,0 , 
all do it is quite dangerous to use with strlen since it stops at the first encountering with a zero 
what if the arr had a zero in between the first 7 bytes
arr[10]={2,8,0,1,7,1,0,0,0,0} then only (2,8) would be kept and
and the size would be of 2
*/
memcpy(copyOfArr,arr,sizeof(shortArr)); // copying the bytes from arr to shortArr

CodePudding user response:

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));

CodePudding user response:

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 by ptr to be deallocated, that is, made available for further allocation. If ptr 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 to free or realloc, the behavior is undefined.

  •  Tags:  
  • Related