In a system where I'm limited with CPU power and memory, I was wondering if I can use this trick (which doesn't work) to gain some performance. The goal is to reduce memory and CPU usage.
Let's say I allocated 6*sizeof(int) at some point during runtime and I don't need the first value of the pointer later anymore. At this point I will have a portion of that allocated memory, more specifically 1*sizeof(int) that the program doesn't need and cannot use.
So my first idea is to allocate 5*sizeof(int) in another pointer, move the data through and free the first one, but by doing this I will have to use more memory for a short duration (2 pointers) and by moving data from addresses to other addresses I'll lose CPU performance.
My second idea was better in theory but it didn't work, instead of moving data, I can directly allocate the second pointer to the second address of the first pointer, and by doing that, I didn't have to use the CPU to move data and my new pointer is working fine until I free the old one... Basically this is the code I tried:
void Print(int* k, int size)
{
for(int i=0;i<size;i++)
{
printf("%d, ",k[i]);
}
}
void Scan(int* k, int size)
{
for(int i=0;i<size;i++)
{
k[i] = i+1;
}
}
int main() {
int* a = malloc(6 * sizeof(int));
Scan(a,6);
Print(a, 6);
int* p = malloc(5 * sizeof(int));
p = a+1;
free(a);
Print(p, 5);
return 0;
}
Is there a way to make it work please?