Reputation: 312
I'm having difficulties reducing the memory allocated by a pointer. This is done as this pointer points to a char array which will store bytes but the number of bytes can differ.
The following struct is used:
struct packet {
unsigned char *data
}
In my code, I first allocate memory for the packet and data:
struct packet *pack;
pack = malloc(sizeof(struct packet));
pack->data = malloc(MAXSIZE);
MAXSIZE is the maximum size that will be read at once (256 bytes).
After reading the file with a buffer and setting the data to the buffer using: pack->data= &buffer
, I read the remaining bytes in the file (calculated using stat() and subtracting MAXSIZE each time until we have less than MAXSIZE left.)
At this point, I want to make the data pointer allocate less memory than MAXSIZE as the data will not be as large, I try the following code but it fails and results in "core dumped":
free(pack->data);
printf("Memory freed.") // This never gets printed so there is an issue with free...
pack->data = malloc(remaining_size);
The remaining_size is calculated correctly so I know it should allocate correctly. Am I taking the wrong approach? I've also tried realloc()
but I get the same result.
Would really appreciate some help, this is a general problem but I need something similar to work for a school project requiring all memory to be freed. If I can solve this issue, I should be able to free the memory. Thanks!
Edit: If I remove the free() call and simply malloc() again, it works but I believe this is the wrong approach as the old allocated space is gone forever and I can never free it.
Upvotes: 2
Views: 1981
Reputation: 370455
pack->data = &buffer;
After executing that line, data
will hold the address of the variable buffer
. It will no longer hold the address on the heap that it previously held (and that address is now leaked if you don't hold onto it somewhere else). However free
only works with addresses on the heap, so calling free
on pack->data
invokes undefined behavior.
Upvotes: 6