This question already has answers here:
How do free and malloc work in C?
(8 answers)
Closed 6 years ago.
/*Pointer Array (Dynamic) EXAMPLE*/
int size = 0;
printf("Enter the size of the array you want:\n");
scanf("%d",&size);
int * Dptr = malloc(sizeof(*Dptr)*size);
if(!Dptr)
return -1;
for(int i=0;i<size;i++)
Dptr[i]= -7;
printf("Congratulations, you successfully allocated and wrote to a dynamic array.\n");
free(Dptr); //how does it "know" what to deallocate? Is everything getting proprely reclaimed?
Above the a little doodle in C I wrote, I had a question about memory allocation concerning dynamic arrays. At the end I call the free function to deallocate the memory of the array I allocated, but my question is, how does it "know" how much memory to deallocate? Or, is it just deallocating the first int and leaving everything else dangling? If so, what is the proper way to reclaim this memory?
The free call releases the entire buffer; a single malloc call should correspond to a single free call.
As to how it knows... well, that's going to depend on the implementation. But if you're just looking for peace of mind, consider this:
If the system didn't know how big the buffer was, how would it know where it could start the next dynamic allocation (if you should call malloc again without having freed the first buffer)?
This is all the responsibility of the memory management libraries. It will work in any properly implemented system.
Related
This question already has answers here:
What REALLY happens when you don't free after malloc before program termination?
(20 answers)
Closed 3 years ago.
If I use malloc() to allocate memory and do not use free() to de-allocate the
the memory. why cannot that memory be accessed by other program by just over writing the previous content
void main()
{
int *a; //here a is holding a junk value
MALLOC(a,1,int);
*a=100; //a is holding 100
MALLOC(a,1,int);
*a=200; //a is holding 200
/* so memory location where the value 100 is stored is inaccessible
cannot be reused */
//why can't we just over write that memory space when used next time
}
You are using a very strange macro, the allocations in standard C would read:
int * const a = malloc(sizeof *a);
if (a != NULL)
{
*a = 100;
}
then the second allocation is done without calling free(), and overwriting the contents of a; this is very bad since it leaks the memory. That's why I declared it as * const above, to signal that the pointer variable in typical use should not be overwritten since we want to keep its value.
When your program ends, on typical modern systems, all resources used by that process will be reclaimed by the operating system and the memory will be used for something else.
The need to call free() is mostly about allocations done while your program runs, if the allocations happen repeatedly the process will just grow and grow otherwise.
This question already has answers here:
What's the difference between a VLA and dynamic memory allocation via malloc?
(4 answers)
Closed 6 years ago.
In the following code I'm providing size of array at run time.
#include <stdio.h>
int main()
{
int i;
scanf("%d",&i);
int a[i];
}
Please tell me the difference between the code above and code using malloc().
I know that array store is on the stack and dynamic memory (malloc, calloc etc) is on the heap.
So is my code functioning similar to malloc? If not, please explain.
Apart from your code uses VLA which:
did not exist before C99
were introduced as a new feature in C99
are now an optional feature since C11
The difference is that automatic arrays (VLA or static size ones) are automatically release when they go out of scope, so you cannot return them from a function, while dynamically allocated ones persist until they are explicitely freed - which shall happen before you lose a pointer to them if you do not want a memory leak.
The Above statement works in C99, but there are limitations of using this approach:
int a[i] is variable length array not the memory dynamically
allocated, hence it will store on STACK instead of HEAP "which it does
in case of malloc" hence there will be situation when somebody entered
MAX_INT and your STACK memory limit is very less(Ex : Embedded
Systems) then Stack Corruption might occur.
This question already has answers here:
Variable Sized Arrays vs calloc in C
(5 answers)
Closed 7 years ago.
I was amazed to see that this code is working. I couldn't figure out why
#include<stdio.h>
int main(){
int row,col,i,j;
scanf("%d %d",&row,&col);
int a[row][col];
for(i=0;i<row;i++)
for(j=0;j<col;j++)
scanf("%d",&a[i][j]);
for(i=0;i<row;i++){
for(j=0;j<col;j++)
printf("%d ",a[i][j]);
printf("\n");
}
}
Since C is a compiled language then How it is allocating memory for the array a[row][col] ? Since at the time of compilation the value of row and column are not known, then how it is able to make machine code and set the address space for the program? Why this is working as an interpreter language would have worked, If this is a way to create a dynamic array then why are we taught to use malloc for creating dynamic array in C.
Variable-length arrays have been a standard feature of C since C99.
How it is allocating memory for the array a[row][col]
Once the value of row and col is known, there is no problem for the compiled code to make this allocation in the automatic storage area (commonly referred to as "the stack").
how it is able to make machine code and set the address space for the program?
The compiler squirrels away the values of row and col for internal use by machine code that it generates. Instructions that reference a[i][j] look up the sizes, do the math, add the offset, and get the address, as if row and col were known at compile time.
The feature does change a few other things - for example, sizeof is no longer a purely compile-time operation, because the size of VLAs need to be computed at run-time.
why are we taught to use malloc for creating dynamic array in C.
malloc gives you more flexibility than a VLA. For example, you can return a malloc-created array from your function, while VLA gets automatically deallocated as soon as the function finishes. In addition, malloc is less likely to run your program out of memory, because dynamic storage area is more generously sized than the automatic one.
For example, if you try to enter 2000 2000 for your program, it is likely going to crash. Yet it would have no problem allocating the same amount of memory with malloc:
int (*a)[col] = malloc(row*col*sizeof(int));
That's feature of C99. The reason to use malloc anyway is that it allocates space not on the stack, but the heap - and the heap is where the 'heavy' data should be stored, as the stack space is severely limited. More than that; failure to do a stack allocation typically crashes the program - while allocating with malloc returns a NULL pointer, which allows you to proceed in elegant fashion.
This question already has answers here:
When is malloc necessary in C?
(8 answers)
Closed 8 years ago.
It is often said to use malloc when size is known at run time we could also write
int x;
scanf("%d",&x);
char arr[x];
so why use malloc when we can declare array on the fly.
Writing char arr[x]; will allocate the memory on the stack.
The size of the stack is typically limited to around 1MB. You'll get runtime errors if you exceed this pre-defined amount. Some compilers will allow you to change the stack size, but you'll still hit a limit eventually of many orders of magnitude than you can get with malloc.
VLA [Variable length array] is a concept present in C99 onwards.
malloc() originates much before that.
Also, malloc() and family allocates memory from heap. It does not use the comparatively limited stack space.
OTOH, gcc allocates space for VLAs in the stack itself.
This question already has answers here:
Why freed struct in C still has data?
(7 answers)
Closed 8 years ago.
int main(int argc, char **argv)
{
counter = 0;
int size = 5;
struct trie *mainTrie = malloc(size * sizeof(mainTrie));
test(mainTrie);
printf("%c", mainTrie[2].alphabet);
free(mainTrie->alphabet);
printf("%c", mainTrie[2].alphabet);
return 0;
}
The test functions was just to see how I can use malloc. My experiment was successful except one thing: free(mainTrie).
When I added printf("%c", mainTrie[2].alphabet) after I 'freed' the memory spaces, the output still gave me the same letter that was stored at mainTrie[2].alphabet from method 'test'.
Am I not understanding something? Thanks in advance...
Show us your complete code, specially the maintree struct. It seems like you need to free the maintree variable:
free(maintree);
However, freeing memory means that the piece of memory you reserved will be available to the O.S again. It doesn't mean you actually set that piece of memory tu NULL. Edit: #MattMcNabb "Typically the memory is not released to the OS, just made available for further allocations from the same process. (This depends on a lot of things of course)"
It is possible that you are printing a piece of memory that doesn't belong to your program anymore, but the data hasn't changed yet.
Note these 2 important things from the documentation
A block of memory previously allocated by a call to malloc, calloc or realloc is deallocated, making it available again for further allocations. (just deallocated, doesn't say anything about the values being changed)
If ptr does not point to a block of memory allocated with the above functions, it causes undefined behavior.
If ptr is a null pointer, the function does nothing.
Notice that this function does not change the value of ptr itself, hence it still points to the same (now invalid) location. (so you maybe pointing to a piece of memory you allocated in the past, but it still has the same values, it is possible, it wont happen all the time).