I have a problem in a C program: I would like to free the first element from a dynamic array but I don't know if it is possible nor how I could do it. For instance if I allocate an array A made of 10 integers like this:
int *A;
A=(int*)malloc(sizeof(int)*10);
is it possible to free the first position of the array? In which way?
I must optimize the program so I can't do some memcpy
ignoring the first element or similar stuff because it would be a slowdown.
When you allocate a chuck of memory, you can't deallocate a part of it. It has to be the whole chunk. More specifically, you can only pass to free
exactly what was returned by malloc
/ calloc
/ realloc
.
What you can do is use realloc
to resize a memory region, however this is not something you want to do too frequently as it can affect performance. A good rule is to double the size when you want to expand and half the size when you want to contract.