logo

malloc() vs new C++:ssa

Molemmat malloc() ja uusia C++:ssa käytetään samaan tarkoitukseen. Niitä käytetään muistin varaamiseen ajon aikana. Mutta malloc():lla ja newlla on eri syntaksi. Suurin ero malloc():n ja new välillä on, että new on operaattori, kun taas malloc() on tavallinen kirjastofunktio, joka on ennalta määritetty stdlib otsikkotiedosto.

Mitä uutta?

Uusi on muistinvarausoperaattori, jota käytetään muistin varaamiseen ajon aikana. Uuden operaattorin alustama muisti varataan kasaan. Se palauttaa muistin aloitusosoitteen, joka määritetään muuttujalle. Uuden operaattorin toiminnallisuus C++:ssa on samanlainen kuin malloc()-funktio, jota käytettiin C-ohjelmointikieli . C++ on yhteensopiva myös malloc()-funktion kanssa, mutta uutta operaattoria käytetään enimmäkseen sen etujen vuoksi.

Uuden operaattorin syntaksi

 type variable = new type(parameter_list); 

Yllä olevassa syntaksissa

tyyppi: Se määrittää sen muuttujan tietotyypin, jolle uusi operaattori varaa muistin.

muuttuja: Se on sen muuttujan nimi, joka osoittaa muistiin.

parametriluettelo: Se on luettelo arvoista, jotka alustetaan muuttujaksi.

Uusi operaattori ei käytä sizeof()-operaattoria muistin varaamiseen. Se ei myöskään käytä kokoa, koska uusi operaattori varaa tarpeeksi muistia objektille. Se on konstruktio, joka kutsuu konstruktoria määrityksen yhteydessä alustamaan objektin.

java oops käsitteitä

Kuten tiedämme, uusi operaattori varaa muistin kasaan; jos muistia ei ole saatavilla kasassa ja uusi operaattori yrittää varata muistia, poikkeus heitetään. Jos koodimme ei pysty käsittelemään poikkeusta, ohjelma lopetetaan epänormaalisti.

Ymmärretään uutta operaattoria esimerkin kautta.

 #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<<>

missä,

tyyppi: se on sen muuttujan tietotyyppi, jolle muistia on varattava.

muuttujan_nimi: Se määrittää muistiin osoittavan muuttujan nimen.

(tyyppi*): Sitä käytetään tyyppilähetykseen, jotta voimme saada tietyn tyyppisen osoittimen, joka osoittaa muistiin.

koko(): sizeof()-operaattoria käytetään malloc()-funktiossa allokoinnissa tarvittavan muistikoon saamiseksi.

Huomautus: Malloc()-funktio palauttaa void-osoittimen, joten typecasting vaaditaan eri tyypin määrittämiseksi osoittimelle. sizeof()-operaattori vaaditaan malloc()-funktiossa, koska malloc()-funktio palauttaa raakamuistin, joten sizeof()-operaattori kertoo malloc()-funktiolle, kuinka paljon muistia tarvitaan varaukseen.

Jos muistia ei ole riittävästi, muistin kokoa voidaan muuttaa realloc()-funktiolla. Koska tiedämme, että kaikki dynaamiset muistivaatimukset täyttyvät kasamuistin avulla, malloc()-funktio varaa myös muistin kasaan ja palauttaa osoittimen siihen. Keon muisti on hyvin rajallinen, joten kun koodimme käynnistyy, se merkitsee muistin käytössä ja kun koodimme suorittaa tehtävänsä, se vapauttaa muistin käyttämällä free()-funktiota. Jos muistia ei ole riittävästi ja koodimme yrittää käyttää muistia, malloc()-funktio palauttaa NULL-osoittimen. Malloc()-funktion varaama muisti voidaan vapauttaa käyttämällä free()-funktiota.

Ymmärretään esimerkin kautta.

 #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++)>

Yllä olevassa koodissa kutsumme func()-funktiota. Func()-funktio palauttaa kokonaislukuosoittimen. Func()-funktion sisällä olemme ilmoittaneet *p-osoittimen, ja muisti on varattu tälle osoitinmuuttujalle malloc()-funktiolla. Tässä tapauksessa palautamme osoittimen, jonka muisti on jo vapautettu. Ptr on riippuva osoitin, koska se osoittaa vapautettuun muistipaikkaan. Tai voimme sanoa, että ptr viittaa siihen muistiin, jota osoitin ei osoita.

Tähän mennessä olemme saaneet tietää uudesta operaattorista ja malloc()-funktiosta. Nyt näemme erot uuden operaattorin ja malloc()-funktion välillä.

Erot malloc():n ja new välillä

malloc() vs new C++:ssa
  • Uusi operaattori rakentaa objektin, eli se kutsuu konstruktoria alustamaan objektin malloc() funktio ei kutsu konstruktoria. Uusi operaattori kutsuu rakentajan ja delete-operaattori kutsuu destructorin tuhotakseen objektin. Tämä on suurin ero malloc():n ja new välillä.
  • New on operaattori, kun taas malloc() on ennalta määritetty funktio stdlib-otsikkotiedostossa.
  • Operaattori new voidaan ylikuormittaa, kun taas malloc()-funktiota ei voida ylikuormittaa.
  • Jos kasassa ei ole riittävästi muistia, uusi operaattori heittää poikkeuksen, kun taas malloc()-funktio palauttaa NULL-osoittimen.
  • Uudessa operaattorissa meidän on määritettävä allokoitavien objektien määrä, kun taas malloc()-funktiossa meidän on määritettävä allokoitavien tavujen määrä.
  • Uuden operaattorin tapauksessa meidän on käytettävä delete-operaattoria muistin vapauttamiseen. Mutta malloc()-funktion tapauksessa meidän on käytettävä free()-funktiota muistin vapauttamiseen.

Uuden operaattorin syntaksi

 type reference_variable = new type name; 

missä,

tyyppi: Se määrittää viitemuuttujan tietotyypin.

viitemuuttuja: Se on osoitinmuuttujan nimi.

i d e:n täysi muoto

Uusi: Se on operaattori, jota käytetään muistin varaamiseen.

tyypin nimi: Se voi olla mikä tahansa perustietotyyppi.

Esimerkiksi,

 int *p; p = new int; 

Yllä olevissa lauseissa ilmoitamme kokonaislukuosoittimen muuttujan. Lausunto p = uusi int; varaa muistitilan kokonaislukumuuttujalle.

Mallin malloc() syntaksi on annettu alla:

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

ptr: Se on osoitinmuuttuja.

tietotyyppi: Se voi olla mikä tahansa perustietotyyppi.

Esimerkiksi,

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

Yllä oleva käsky varaa muistin kokonaislukumuuttujalle kasaan ja tallentaa sitten varatun muistin osoitteen 'p'-muuttujaan.

  • Toisaalta malloc()-funktiolla varattu muisti voidaan vapauttaa free()-funktiolla.
  • Kun muisti on varattu uudella operaattorilla, sen kokoa ei voi muuttaa. Toisaalta muisti varataan malloc()-funktiolla; sitten se voidaan jakaa uudelleen käyttämällä realloc()-funktiota.
  • Uuden suoritusaika on pienempi kuin malloc()-funktion, koska new on konstruktio ja malloc on funktio.
  • Uusi operaattori ei palauta erillistä osoitinmuuttujaa; se palauttaa juuri luodun objektin osoitteen. Toisaalta malloc()-funktio palauttaa void-osoittimen, joka voidaan edelleen kirjoittaa tietyllä tyypillä.