logo

malloc() u odnosu na novo u C++

Oba malloc() i new u C++ koriste se za istu svrhu. Koriste se za dodjelu memorije tijekom izvođenja. Ali malloc() i new imaju različitu sintaksu. Glavna razlika između malloc() i new je u tome što je new operator, dok je malloc() standardna funkcija biblioteke koja je unaprijed definirana u stdlib datoteka zaglavlja.

Što je novo?

Novost je operator dodjele memorije koji se koristi za dodjelu memorije tijekom izvođenja. Memorija koju je inicijalizirao new operator alocirana je u gomili. Vraća početnu adresu memorije koja se dodjeljuje varijabli. Funkcionalnost novog operatora u C++ slična je funkciji malloc() koja je korištena u C programski jezik . C++ također je kompatibilan s funkcijom malloc(), ali se uglavnom koristi novi operator zbog svojih prednosti.

Sintaksa novog operatora

 type variable = new type(parameter_list); 

U gornjoj sintaksi

tip: Definira tip podataka varijable za koju je new operator alocirao memoriju.

varijabla: To je naziv varijable koja ukazuje na memoriju.

popis_parametara: To je popis vrijednosti koje su inicijalizirane za varijablu.

New operator ne koristi sizeof() operator za dodjelu memorije. Također ne koristi promjenu veličine jer novi operator dodjeljuje dovoljno memorije za objekt. To je konstrukcija koja poziva konstruktor u vrijeme deklaracije da inicijalizira objekt.

Kao što znamo da new operator dodjeljuje memoriju u gomili; ako memorija nije dostupna u hrpi i novi operator pokuša dodijeliti memoriju, tada se izbacuje iznimka. Ako naš kod nije u stanju obraditi iznimku, tada će se program nenormalno prekinuti.

Razmotrimo novi operator kroz primjer.

 #include using namespace std; int main() { int *ptr; // integer pointer variable declaration ptr=new int; // allocating memory to the pointer variable ptr. std::cout &lt;&lt; &apos;Enter the number : &apos; &lt;&gt;*ptr; std::cout &lt;&lt; &apos;Entered number is &apos; &lt;<*ptr<< std::endl; return 0; } < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/c-tutorial/80/malloc-vs-new-c.webp" alt="malloc() vs new in C++"> <h3>What is malloc()?</h3> <p>A malloc() is a function that allocates memory at the runtime. This function returns the void pointer, which means that it can be assigned to any pointer type. This void pointer can be further typecast to get the pointer that points to the memory of a specified type.</p> <p>The syntax of the malloc() function is given below:</p> <pre> type variable_name = (type *)malloc(sizeof(type)); </pre> <p> <strong>where,</strong> </p> <p> <strong>type:</strong> it is the datatype of the variable for which the memory has to be allocated.</p> <p> <strong>variable_name:</strong> It defines the name of the variable that points to the memory.</p> <p> <strong>(type*):</strong> It is used for typecasting so that we can get the pointer of a specified type that points to the memory.</p> <p> <strong>sizeof():</strong> The sizeof() operator is used in the malloc() function to obtain the memory size required for the allocation.</p> <h4>Note: The malloc() function returns the void pointer, so typecasting is required to assign a different type to the pointer. The sizeof() operator is required in the malloc() function as the malloc() function returns the raw memory, so the sizeof() operator will tell the malloc() function how much memory is required for the allocation.</h4> <p>If the sufficient memory is not available, then the memory can be resized using realloc() function. As we know that all the dynamic memory requirements are fulfilled using heap memory, so malloc() function also allocates the memory in a heap and returns the pointer to it. The heap memory is very limited, so when our code starts execution, it marks the memory in use, and when our code completes its task, then it frees the memory by using the free() function. If the sufficient memory is not available, and our code tries to access the memory, then the malloc() function returns the NULL pointer. The memory which is allocated by the malloc() function can be deallocated by using the free() function.</p> <p> <strong>Let&apos;s understand through an example.</strong> </p> <pre> #include #include using namespace std; int main() { int len; // variable declaration std::cout &lt;&lt; &apos;Enter the count of numbers :&apos; &lt;&gt; len; int *ptr; // pointer variable declaration ptr=(int*) malloc(sizeof(int)*len); // allocating memory to the poiner variable for(int i=0;i<len;i++) { std::cout << 'enter a number : ' <> *(ptr+i); } std::cout &lt;&lt; &apos;Entered elements are : &apos; &lt;&lt; std::endl; for(int i=0;i<len;i++) { std::cout << *(ptr+i) std::endl; } free(ptr); return 0; < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/c-tutorial/80/malloc-vs-new-c-2.webp" alt="malloc() vs new in C++"> <p>If we do not use the <strong>free()</strong> function at the correct place, then it can lead to the cause of the dangling pointer. <strong>Let&apos;s understand this scenario through an example.</strong> </p> <pre> #include #include using namespace std; int *func() { int *p; p=(int*) malloc(sizeof(int)); free(p); return p; } int main() { int *ptr; ptr=func(); free(ptr); return 0; } </pre> <p>In the above code, we are calling the func() function. The func() function returns the integer pointer. Inside the func() function, we have declared a *p pointer, and the memory is allocated to this pointer variable using malloc() function. In this case, we are returning the pointer whose memory is already released. The ptr is a dangling pointer as it is pointing to the released memory location. Or we can say ptr is referring to that memory which is not pointed by the pointer.</p> <p>Till now, we get to know about the new operator and the malloc() function. Now, we will see the differences between the new operator and the malloc() function.</p> <h3>Differences between the malloc() and new</h3> <img src="//techcodeview.com/img/c-tutorial/80/malloc-vs-new-c-3.webp" alt="malloc() vs new in C++"> <ul> <li>The new operator constructs an object, i.e., it calls the constructor to initialize an object while <strong>malloc()</strong> function does not call the constructor. The new operator invokes the constructor, and the delete operator invokes the destructor to destroy the object. This is the biggest difference between the malloc() and new.</li> <li>The new is an operator, while malloc() is a predefined function in the stdlib header file.</li> <li>The operator new can be overloaded while the malloc() function cannot be overloaded.</li> <li>If the sufficient memory is not available in a heap, then the new operator will throw an exception while the malloc() function returns a NULL pointer.</li> <li>In the new operator, we need to specify the number of objects to be allocated while in malloc() function, we need to specify the number of bytes to be allocated.</li> <li>In the case of a new operator, we have to use the delete operator to deallocate the memory. But in the case of malloc() function, we have to use the free() function to deallocate the memory.</li> </ul> <p> <strong>Syntax of new operator</strong> </p> <pre> type reference_variable = new type name; </pre> <p> <strong>where,</strong> </p> <p> <strong>type:</strong> It defines the data type of the reference variable.</p> <p> <strong>reference_variable:</strong> It is the name of the pointer variable.</p> <p> <strong>new:</strong> It is an operator used for allocating the memory.</p> <p> <strong>type name:</strong> It can be any basic data type.</p> <p> <strong>For example,</strong> </p> <pre> int *p; p = new int; </pre> <p>In the above statements, we are declaring an integer pointer variable. The statement <strong>p = new int;</strong> allocates the memory space for an integer variable.</p> <p> <strong>Syntax of malloc() is given below:</strong> </p> <pre> int *ptr = (data_type*) malloc(sizeof(data_type)); </pre> <p> <strong>ptr:</strong> It is a pointer variable.</p> <p> <strong>data_type:</strong> It can be any basic data type.</p> <p> <strong>For example,</strong> </p> <pre> int *p; p = (int *) malloc(sizeof(int)) </pre> <p>The above statement will allocate the memory for an integer variable in a heap, and then stores the address of the reserved memory in &apos;p&apos; variable.</p> <ul> <li>On the other hand, the memory allocated using malloc() function can be deallocated using the free() function.</li> <li>Once the memory is allocated using the new operator, then it cannot be resized. On the other hand, the memory is allocated using malloc() function; then, it can be reallocated using realloc() function.</li> <li>The execution time of new is less than the malloc() function as new is a construct, and malloc is a function.</li> <li>The new operator does not return the separate pointer variable; it returns the address of the newly created object. On the other hand, the malloc() function returns the void pointer which can be further typecast in a specified type.</li> </ul> <hr></len;i++)></len;i++)></pre></*ptr<<>

gdje,

tip: to je tip podataka varijable za koju se mora dodijeliti memorija.

naziv_varijable: Definira naziv varijable koja ukazuje na memoriju.

ukloniti zadnji znak iz niza

(tip*): Koristi se za tipiziranje tako da možemo dobiti pokazivač određenog tipa koji pokazuje na memoriju.

veličina(): Operator sizeof() koristi se u funkciji malloc() za dobivanje veličine memorije potrebne za dodjelu.

Napomena: funkcija malloc() vraća void pokazivač, pa je potrebno prevođenje tipa da bi se pokazivaču dodijelio drugi tip. Operator sizeof() potreban je u funkciji malloc() budući da funkcija malloc() vraća neobrađenu memoriju, pa će operator sizeof() reći funkciji malloc() koliko je memorije potrebno za dodjelu.

Ako dovoljno memorije nije dostupno, veličina memorije se može promijeniti pomoću funkcije realloc(). Kako znamo da su svi zahtjevi dinamičke memorije ispunjeni korištenjem heap memorije, funkcija malloc() također alocira memoriju u heap i vraća pokazivač na nju. Memorija gomile je vrlo ograničena, tako da kada naš kod krene s izvođenjem, označava memoriju u upotrebi, a kada naš kod završi svoj zadatak, oslobađa memoriju pomoću funkcije free(). Ako nema dovoljno memorije, a naš kod pokušava pristupiti memoriji, tada funkcija malloc() vraća pokazivač NULL. Memorija koju dodjeljuje funkcija malloc() može se osloboditi pomoću funkcije free().

Shvatimo kroz primjer.

 #include #include using namespace std; int main() { int len; // variable declaration std::cout &lt;&lt; &apos;Enter the count of numbers :&apos; &lt;&gt; len; int *ptr; // pointer variable declaration ptr=(int*) malloc(sizeof(int)*len); // allocating memory to the poiner variable for(int i=0;i<len;i++) { std::cout << \'enter a number : \' <> *(ptr+i); } std::cout &lt;&lt; &apos;Entered elements are : &apos; &lt;&lt; std::endl; for(int i=0;i<len;i++) { std::cout << *(ptr+i) std::endl; } free(ptr); return 0; < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/c-tutorial/80/malloc-vs-new-c-2.webp" alt="malloc() vs new in C++"> <p>If we do not use the <strong>free()</strong> function at the correct place, then it can lead to the cause of the dangling pointer. <strong>Let&apos;s understand this scenario through an example.</strong> </p> <pre> #include #include using namespace std; int *func() { int *p; p=(int*) malloc(sizeof(int)); free(p); return p; } int main() { int *ptr; ptr=func(); free(ptr); return 0; } </pre> <p>In the above code, we are calling the func() function. The func() function returns the integer pointer. Inside the func() function, we have declared a *p pointer, and the memory is allocated to this pointer variable using malloc() function. In this case, we are returning the pointer whose memory is already released. The ptr is a dangling pointer as it is pointing to the released memory location. Or we can say ptr is referring to that memory which is not pointed by the pointer.</p> <p>Till now, we get to know about the new operator and the malloc() function. Now, we will see the differences between the new operator and the malloc() function.</p> <h3>Differences between the malloc() and new</h3> <img src="//techcodeview.com/img/c-tutorial/80/malloc-vs-new-c-3.webp" alt="malloc() vs new in C++"> <ul> <li>The new operator constructs an object, i.e., it calls the constructor to initialize an object while <strong>malloc()</strong> function does not call the constructor. The new operator invokes the constructor, and the delete operator invokes the destructor to destroy the object. This is the biggest difference between the malloc() and new.</li> <li>The new is an operator, while malloc() is a predefined function in the stdlib header file.</li> <li>The operator new can be overloaded while the malloc() function cannot be overloaded.</li> <li>If the sufficient memory is not available in a heap, then the new operator will throw an exception while the malloc() function returns a NULL pointer.</li> <li>In the new operator, we need to specify the number of objects to be allocated while in malloc() function, we need to specify the number of bytes to be allocated.</li> <li>In the case of a new operator, we have to use the delete operator to deallocate the memory. But in the case of malloc() function, we have to use the free() function to deallocate the memory.</li> </ul> <p> <strong>Syntax of new operator</strong> </p> <pre> type reference_variable = new type name; </pre> <p> <strong>where,</strong> </p> <p> <strong>type:</strong> It defines the data type of the reference variable.</p> <p> <strong>reference_variable:</strong> It is the name of the pointer variable.</p> <p> <strong>new:</strong> It is an operator used for allocating the memory.</p> <p> <strong>type name:</strong> It can be any basic data type.</p> <p> <strong>For example,</strong> </p> <pre> int *p; p = new int; </pre> <p>In the above statements, we are declaring an integer pointer variable. The statement <strong>p = new int;</strong> allocates the memory space for an integer variable.</p> <p> <strong>Syntax of malloc() is given below:</strong> </p> <pre> int *ptr = (data_type*) malloc(sizeof(data_type)); </pre> <p> <strong>ptr:</strong> It is a pointer variable.</p> <p> <strong>data_type:</strong> It can be any basic data type.</p> <p> <strong>For example,</strong> </p> <pre> int *p; p = (int *) malloc(sizeof(int)) </pre> <p>The above statement will allocate the memory for an integer variable in a heap, and then stores the address of the reserved memory in &apos;p&apos; variable.</p> <ul> <li>On the other hand, the memory allocated using malloc() function can be deallocated using the free() function.</li> <li>Once the memory is allocated using the new operator, then it cannot be resized. On the other hand, the memory is allocated using malloc() function; then, it can be reallocated using realloc() function.</li> <li>The execution time of new is less than the malloc() function as new is a construct, and malloc is a function.</li> <li>The new operator does not return the separate pointer variable; it returns the address of the newly created object. On the other hand, the malloc() function returns the void pointer which can be further typecast in a specified type.</li> </ul> <hr></len;i++)></len;i++)>

U gornjem kodu pozivamo funkciju func(). Funkcija func() vraća pokazivač cijelog broja. Unutar funkcije func(), deklarirali smo *p pointer, a memorija je dodijeljena ovoj varijabli pokazivača pomoću funkcije malloc(). U ovom slučaju vraćamo pokazivač čija je memorija već oslobođena. PTR je viseći pokazivač jer pokazuje na oslobođenu memorijsku lokaciju. Ili možemo reći da se ptr odnosi na onu memoriju na koju pokazivač ne pokazuje.

Do sada smo se upoznali s novim operatorom i funkcijom malloc(). Sada ćemo vidjeti razlike između new operatora i malloc() funkcije.

Razlike između malloc() i new

malloc() u odnosu na novo u C++
  • New operator konstruira objekt, tj. poziva konstruktor da inicijalizira objekt while malloc() funkcija ne poziva konstruktor. Operator new poziva konstruktor, a operator delete poziva destruktor da uništi objekt. Ovo je najveća razlika između malloc() i new.
  • New je operator, dok je malloc() unaprijed definirana funkcija u datoteci zaglavlja stdlib.
  • Operator new može se preopteretiti dok se funkcija malloc() ne može preopteretiti.
  • Ako dovoljno memorije nije dostupno u hrpi, tada će novi operator izbaciti iznimku dok funkcija malloc() vraća NULL pokazivač.
  • U novom operatoru moramo navesti broj objekata koji će se dodijeliti, dok u funkciji malloc() moramo navesti broj bajtova koji će se dodijeliti.
  • U slučaju novog operatora, moramo upotrijebiti operator delete da oslobodimo memoriju. Ali u slučaju malloc() funkcije, moramo koristiti free() funkciju za oslobađanje memorije.

Sintaksa novog operatora

 type reference_variable = new type name; 

gdje,

tip: Definira tip podataka referentne varijable.

linux datoteke

referentna_varijabla: To je naziv varijable pokazivača.

novi: To je operator koji se koristi za dodjelu memorije.

ime tipa: To može biti bilo koji osnovni tip podataka.

Na primjer,

 int *p; p = new int; 

U gornjim izjavama deklariramo varijablu pokazivača cijelog broja. Izjava p = novi int; dodjeljuje memorijski prostor za cjelobrojnu varijablu.

Sintaksa malloc() data je u nastavku:

 int *ptr = (data_type*) malloc(sizeof(data_type)); 

ptr: To je pokazivačka varijabla.

tip podataka: To može biti bilo koji osnovni tip podataka.

Na primjer,

 int *p; p = (int *) malloc(sizeof(int)) 

Gornja izjava će dodijeliti memoriju za cjelobrojnu varijablu u gomili, a zatim će pohraniti adresu rezervirane memorije u 'p' varijabli.

  • S druge strane, memorija dodijeljena pomoću funkcije malloc() može se osloboditi pomoću funkcije free().
  • Jednom kada se memorija dodijeli korištenjem novog operatora, tada joj se ne može promijeniti veličina. S druge strane, memorija se dodjeljuje pomoću funkcije malloc(); tada se može preraspodijeliti pomoću funkcije realloc().
  • Vrijeme izvršenja new manje je od funkcije malloc() budući da je new konstrukcija, a malloc funkcija.
  • Novi operator ne vraća odvojenu varijablu pokazivača; vraća adresu novostvorenog objekta. S druge strane, funkcija malloc() vraća void pointer koji se može dalje tipizirati u određenom tipu.