+ 7

dynamic allocate and free in c

int *p=malloc(4*sizeof(int)); p+=3; free(p); in this code I reserved for 4 element and free the third one shall all memory that I allocated be freed ? or just the third element

21st May 2019, 11:16 PM
ABADA S
ABADA S - avatar
8 ответов
+ 7
You'd have to free it all or reallocate(). This would cause a memory corruption as your pointer points to allocated memory for an array of 4 integers. No storage is allocated for each integer itself, so you'd be attempting to free memory that was not allocated. :-) You'd probably want an array of integer pointers like so: int **p = malloc(4 * sizeof(int *)); for (int i = 0; i < 4; i++) { p[i] = malloc(sizeof(int)); // Alloc mem for a single int *p[i] = i; // Set its value } // free one element in the array free(p[3]); . . . free() the others when necessary before freeing p. // Free the array free(p);
22nd May 2019, 1:35 AM
Komodo64
Komodo64 - avatar
+ 6
all memory you allocated will be free after they are been used up, and that's not freeing the third or something, you freed the entire memory allocated to that pointer so that you can reuse it, the reason why you need to free it is because on the heap nothing works automatically, you are in control and if you do not free already use memory all the time the data will be stick there, if it get filled up hmmmm.... let me check up what will happen
22nd May 2019, 1:21 AM
✳AsterisK✳
✳AsterisK✳ - avatar
+ 6
Just a reminder that when you do p+=3, you are now pointing to the 4th integer in the block. BTW I tried to test a code related to this and was confused about the result, so I posted the following question: https://www.sololearn.com/Discuss/1811123/?ref=app
22nd May 2019, 2:47 AM
Sonic
Sonic - avatar
+ 4
thanks for helping ~ swim ~ I got it
22nd May 2019, 2:17 AM
ABADA S
ABADA S - avatar
+ 3
thanks guys soo when I allocate a memory it will be a single block , when I free it whenever the pointer is pointing to any address that is contained in this memory it will free the hole block but when I allocate using calloc is the same thing will happen ?
22nd May 2019, 1:46 AM
ABADA S
ABADA S - avatar