Reputation: 667
I am not understanding malloc very well, are those created with malloc just created on the heap?
Upvotes: 0
Views: 104
Reputation: 25286
Your question is "How are arrays that are generated via malloc different from those that are not?"
Answer: there is no difference as far as the C language is concerned. C takes an array address and does indexing relative to it, so it doesn't matter if the array was allocated on the heap or was statically declared.
int a[10];
int *aa;
int *b;
b= a;
b[3]= 4;
aa= calloc(10, sizeof(int));
b= aa;
b[3]= 4;
Note: malloc returns non zeroed memory; calloc returns zeroed memory AND ensuers the returned block is suitably aligned.
Upvotes: 0
Reputation: 50
The arrays in stack and heap are no different regarding usage. Both are memory--they are just different in terms of allocation. malloc
internally calls brk()
or sbrk()
to alter the "program break", i.e the program address space as per your malloced size requirement.
You use malloc when you don't exactly know how much memory to allocate. Or if you need to reuse the memory, because you cannot constantly allocate 1000 arrays of size 10 when using only one or two at a time. Then go for malloc, because you can free memory once you have finished.
Note: Don't ever try to free()
statically allocated variables!
Upvotes: 2
Reputation: 753685
One more difference (not yet mentioned in other answers) is that arrays created by malloc()
are anonymous — you have a pointer to the data, but no name for the data.
Upvotes: 2
Reputation: 7824
Yes when you malloc you are allocating in the heap.
The malloc function does a request for a block of memory from the heap. If the request is granted, the operating system will reserve the requested amount of memory that you asked for.
You should use malloc when you have data that must have a lifetime different than the code scope where it was allocated. For example: you malloc in a function, you store/keep a pointer to that allocated space and then you can use it in another function.
Another advantage, in contrast to stack allocation, is that you can check if malloc failed, when let's say you don't have enough free memory.
Side note: don't forget to free
what you malloc
.
Upvotes: 3
Reputation: 1375
Allocates requested size of bytes and returns a pointer first byte of allocated space
ptr=(cast-type*)malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
Example
ptr=(int*)malloc(100*sizeof(int));
It is used when you want to allocated the memory dynamically(during Run-time). usually every program is associated with heap memory when you run. Hence you should return it back when done using memory by using free().
Upvotes: 0