what is the difference between new and malloc in c. when to use new and when to use malloc??
Hoot! You just asked your first question! Hang tight while I find people to answer it for you. You can thank people who give you good answers by clicking the 'Good Answer' button on the right!
new is not in c .It is in c++. malloc: memory allocation for a pointer.It is run time allocation. The function malloc is used to allocate a certain amount of memory during the execution of a program. The malloc function will request a block of memory from the heap. If the request is granted, the operating system will reserve the requested amount of memory. example: #include<stdio.h> int main() { int *ptr_one; ptr_one = (int *)malloc(sizeof(int)); if (ptr_one == 0) { printf("ERROR: Out of memory\n"); return 1; } *ptr_one = 25; printf("%d\n", *ptr_one); free(ptr_one); return 0; }
New is a operator where as Malloc is a function.Malloc we need to specify the size of memory for our data types. But in case of New we do not need to specify the size. malloc return void* by default ,we need to typecast pointer returned from malloc but in case of new there is no need to typecast ex: int *a; a=(int*)malloc(sizeof(int)); a= new int;
Join our real-time social learning platform and learn together with your friends!