logo

malloc() versus nieuw in C++

Beide malloc() en nieuw in C++ worden voor hetzelfde doel gebruikt. Ze worden gebruikt voor het toewijzen van geheugen tijdens de runtime. Maar malloc() en new hebben een verschillende syntaxis. Het belangrijkste verschil tussen malloc() en new is dat new een operator is, terwijl malloc() een standaardbibliotheekfunctie is die vooraf is gedefinieerd in een operator. stdlib header-bestand.

Wat is nieuw?

Het nieuwe is een geheugentoewijzingsoperator, die wordt gebruikt om het geheugen tijdens runtime toe te wijzen. Het door de nieuwe operator geïnitialiseerde geheugen wordt in een heap toegewezen. Het retourneert het startadres van het geheugen, dat aan de variabele wordt toegewezen. De functionaliteit van de nieuwe operator in C++ is vergelijkbaar met de malloc()-functie, die werd gebruikt in de C-programmeertaal . C++ is ook compatibel met de functie malloc(), maar de nieuwe operator wordt vooral gebruikt vanwege de voordelen ervan.

Syntaxis van nieuwe operator

 type variable = new type(parameter_list); 

In de bovenstaande syntaxis

type: Het definieert het datatype van de variabele waarvoor het geheugen wordt toegewezen door de nieuwe operator.

variabele: Het is de naam van de variabele die naar het geheugen verwijst.

parameterlijst: Het is de lijst met waarden die zijn geïnitialiseerd voor een variabele.

De operator new gebruikt de operator sizeof() niet om het geheugen toe te wijzen. Het maakt ook geen gebruik van de resize-functie, omdat de new-operator voldoende geheugen voor een object toewijst. Het is een constructie die de constructor op het moment van declaratie aanroept om een ​​object te initialiseren.

Zoals we weten, wijst de nieuwe operator het geheugen in een heap toe; als het geheugen niet beschikbaar is in een heap en de nieuwe operator probeert het geheugen toe te wijzen, wordt de uitzondering gegenereerd. Als onze code de uitzondering niet aankan, wordt het programma abnormaal beëindigd.

Laten we de nieuwe operator begrijpen aan de hand van een voorbeeld.

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

waar,

type: het is het datatype van de variabele waarvoor het geheugen moet worden toegewezen.

variabele_naam: Het definieert de naam van de variabele die naar het geheugen verwijst.

(type*): Het wordt gebruikt voor typecasting, zodat we de aanwijzer van een opgegeven type kunnen krijgen die naar het geheugen verwijst.

De grootte van(): De operator sizeof() wordt in de functie malloc() gebruikt om de geheugengrootte te verkrijgen die nodig is voor de toewijzing.

Opmerking: de functie malloc() retourneert de void-aanwijzer, dus typecasting is vereist om een ​​ander type aan de aanwijzer toe te wijzen. De operator sizeof() is vereist in de functie malloc() omdat de functie malloc() het onbewerkte geheugen retourneert, dus de operator sizeof() zal de functie malloc() vertellen hoeveel geheugen er nodig is voor de toewijzing.

Als er niet voldoende geheugen beschikbaar is, kan de grootte van het geheugen worden aangepast met behulp van de functie realloc(). Omdat we weten dat aan alle dynamische geheugenvereisten wordt voldaan met behulp van heap-geheugen, wijst de functie malloc() ook het geheugen toe aan een heap en retourneert de pointer ernaar. Het heap-geheugen is zeer beperkt, dus wanneer onze code begint te worden uitgevoerd, markeert deze het geheugen dat in gebruik is, en wanneer onze code zijn taak voltooit, wordt het geheugen vrijgemaakt door de functie free() te gebruiken. Als er niet voldoende geheugen beschikbaar is en onze code probeert toegang te krijgen tot het geheugen, retourneert de functie malloc() de NULL-aanwijzer. Het geheugen dat wordt toegewezen door de malloc()-functie kan worden opgeheven met behulp van de free()-functie.

Laten we het begrijpen aan de hand van een voorbeeld.

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

In de bovenstaande code roepen we de functie func() aan. De functie func() retourneert de integer-aanwijzer. Binnen de func()-functie hebben we een *p-pointer gedeclareerd, en het geheugen wordt aan deze pointervariabele toegewezen met behulp van de malloc()-functie. In dit geval retourneren we de aanwijzer waarvan het geheugen al is vrijgegeven. De ptr is een bungelende aanwijzer omdat deze naar de vrijgegeven geheugenlocatie wijst. Of we kunnen zeggen dat ptr verwijst naar dat geheugen waarnaar de aanwijzer niet verwijst.

Tot nu toe maken we kennis met de nieuwe operator en de malloc()-functie. Nu zullen we de verschillen zien tussen de nieuwe operator en de malloc() functie.

Verschillen tussen malloc() en new

malloc() versus nieuw in C++
  • De nieuwe operator construeert een object, d.w.z. hij roept de constructor aan om een ​​object while te initialiseren malloc() functie roept de constructor niet aan. De operator new roept de constructor aan, en de operator delete roept de destructor aan om het object te vernietigen. Dit is het grootste verschil tussen malloc() en new.
  • De nieuwe is een operator, terwijl malloc() een vooraf gedefinieerde functie is in het stdlib-headerbestand.
  • De operator new kan overbelast worden, terwijl de functie malloc() niet overbelast kan worden.
  • Als er niet voldoende geheugen beschikbaar is in een heap, genereert de nieuwe operator een uitzondering terwijl de malloc()-functie een NULL-aanwijzer retourneert.
  • In de nieuwe operator moeten we het aantal toe te wijzen objecten specificeren, terwijl we in de functie malloc() het aantal toe te wijzen bytes moeten specificeren.
  • In het geval van een nieuwe operator moeten we de verwijderoperator gebruiken om de toewijzing van het geheugen ongedaan te maken. Maar in het geval van de functie malloc() moeten we de functie free() gebruiken om de toewijzing van het geheugen ongedaan te maken.

Syntaxis van nieuwe operator

 type reference_variable = new type name; 

waar,

type: Het definieert het gegevenstype van de referentievariabele.

referentie_variabele: Het is de naam van de pointervariabele.

nieuw: Het is een operator die wordt gebruikt voor het toewijzen van geheugen.

typenaam: Het kan elk basisgegevenstype zijn.

Bijvoorbeeld,

runa's in powershell
 int *p; p = new int; 

In de bovenstaande uitspraken declareren we een integer-pointervariabele. De verklaring p = nieuwe int; wijst de geheugenruimte toe voor een integer-variabele.

De syntaxis van malloc() wordt hieronder gegeven:

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

ptr: Het is een pointervariabele.

data type: Het kan elk basisgegevenstype zijn.

Bijvoorbeeld,

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

De bovenstaande verklaring wijst het geheugen voor een integer-variabele toe in een heap, en slaat vervolgens het adres van het gereserveerde geheugen op in de 'p'-variabele.

  • Aan de andere kant kan het geheugen dat is toegewezen met de functie malloc() worden opgeheven met behulp van de functie free().
  • Zodra het geheugen is toegewezen met behulp van de nieuwe operator, kan de grootte ervan niet meer worden gewijzigd. Aan de andere kant wordt het geheugen toegewezen met behulp van de malloc()-functie; vervolgens kan het opnieuw worden toegewezen met behulp van de functie realloc().
  • De uitvoeringstijd van new is korter dan die van de malloc()-functie, aangezien new een constructie is en malloc een functie.
  • De nieuwe operator retourneert niet de afzonderlijke pointervariabele; het retourneert het adres van het nieuw gemaakte object. Aan de andere kant retourneert de functie malloc() de void-aanwijzer die verder kan worden getypeerd in een opgegeven type.