logo

malloc() vs. new in C++

Beide malloc() und new in C++ werden für denselben Zweck verwendet. Sie werden zur Speicherzuweisung zur Laufzeit verwendet. Aber malloc() und new haben unterschiedliche Syntax. Der Hauptunterschied zwischen malloc() und new besteht darin, dass new ein Operator ist, während malloc() eine Standardbibliotheksfunktion ist, die in a vordefiniert ist stdlib Header-Datei.

Was ist neu?

Das Neue ist ein Speicherzuweisungsoperator, der zum Zuweisen des Speichers zur Laufzeit verwendet wird. Der vom neuen Operator initialisierte Speicher wird in einem Heap zugewiesen. Es gibt die Startadresse des Speichers zurück, die der Variablen zugewiesen wird. Die Funktionalität des neuen Operators in C++ ähnelt der Funktion malloc(), die in verwendet wurde C-Programmiersprache . C++ ist auch mit der Funktion malloc() kompatibel, aber der neue Operator wird aufgrund seiner Vorteile hauptsächlich verwendet.

Syntax des neuen Operators

blockierte Kontakte
 type variable = new type(parameter_list); 

In der obigen Syntax

Typ: Es definiert den Datentyp der Variablen, für die der neue Operator den Speicher zuweist.

Variable: Es ist der Name der Variablen, die auf den Speicher verweist.

Parameterliste: Es handelt sich um die Liste der Werte, die für eine Variable initialisiert werden.

Der neue Operator verwendet nicht den sizeof()-Operator, um den Speicher zuzuweisen. Außerdem wird die Größenänderung nicht verwendet, da der neue Operator ausreichend Speicher für ein Objekt zuweist. Es handelt sich um ein Konstrukt, das zum Zeitpunkt der Deklaration den Konstruktor aufruft, um ein Objekt zu initialisieren.

manuelle Prüfung

Wie wir wissen, weist der neue Operator den Speicher in einem Heap zu; Wenn der Speicher in einem Heap nicht verfügbar ist und der neue Operator versucht, den Speicher zuzuweisen, wird die Ausnahme ausgelöst. Wenn unser Code die Ausnahme nicht verarbeiten kann, wird das Programm abnormal beendet.

Lassen Sie uns den neuen Operator anhand eines Beispiels verstehen.

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

Wo,

Typ: Es ist der Datentyp der Variablen, für die der Speicher zugewiesen werden muss.

Variablennamen: Es definiert den Namen der Variablen, die auf den Speicher zeigt.

(Typ*): Es wird zur Typumwandlung verwendet, damit wir den Zeiger eines bestimmten Typs erhalten können, der auf den Speicher zeigt.

Größe von(): Der Operator sizeof() wird in der Funktion malloc() verwendet, um die für die Zuweisung erforderliche Speichergröße zu ermitteln.

Hinweis: Die Funktion malloc() gibt den void-Zeiger zurück, daher ist eine Typumwandlung erforderlich, um dem Zeiger einen anderen Typ zuzuweisen. Der Operator sizeof() ist in der Funktion malloc() erforderlich, da die Funktion malloc() den Rohspeicher zurückgibt. Daher teilt der Operator sizeof() der Funktion malloc() mit, wie viel Speicher für die Zuweisung erforderlich ist.

Wenn nicht genügend Speicher verfügbar ist, kann die Größe des Speichers mithilfe der Funktion realloc() geändert werden. Da wir wissen, dass alle dynamischen Speicheranforderungen durch Heap-Speicher erfüllt werden, weist die Funktion malloc() auch den Speicher in einem Heap zu und gibt den Zeiger darauf zurück. Der Heap-Speicher ist sehr begrenzt. Wenn unser Code also mit der Ausführung beginnt, markiert er den verwendeten Speicher, und wenn unser Code seine Aufgabe abschließt, gibt er den Speicher mithilfe der Funktion free() frei. Wenn nicht genügend Speicher verfügbar ist und unser Code versucht, auf den Speicher zuzugreifen, gibt die Funktion malloc() den NULL-Zeiger zurück. Der von der malloc()-Funktion zugewiesene Speicher kann mithilfe der free()-Funktion freigegeben werden.

Was ist das Internet

Lassen Sie es uns anhand eines Beispiels verstehen.

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

Im obigen Code rufen wir die Funktion func() auf. Die Funktion func() gibt den ganzzahligen Zeiger zurück. Innerhalb der Funktion func() haben wir einen *p-Zeiger deklariert und der Speicher wird dieser Zeigervariablen mithilfe der Funktion malloc() zugewiesen. In diesem Fall geben wir den Zeiger zurück, dessen Speicher bereits freigegeben ist. Der ptr ist ein baumelnder Zeiger, da er auf den freigegebenen Speicherort zeigt. Oder wir können sagen, ptr bezieht sich auf den Speicher, auf den der Zeiger nicht zeigt.

Bisher lernen wir den neuen Operator und die Funktion malloc() kennen. Jetzt werden wir die Unterschiede zwischen dem neuen Operator und der Funktion malloc() sehen.

Unterschiede zwischen malloc() und new

malloc() vs. new in C++
  • Der neue Operator erstellt ein Objekt, d. h. er ruft den Konstruktor auf, um ein Objekt zu initialisieren malloc() Die Funktion ruft den Konstruktor nicht auf. Der neue Operator ruft den Konstruktor auf, und der Löschoperator ruft den Destruktor auf, um das Objekt zu zerstören. Dies ist der größte Unterschied zwischen malloc() und new.
  • new ist ein Operator, während malloc() eine vordefinierte Funktion in der stdlib-Headerdatei ist.
  • Der Operator new kann überladen werden, während die Funktion malloc() nicht überladen werden kann.
  • Wenn in einem Heap nicht genügend Speicher verfügbar ist, löst der neue Operator eine Ausnahme aus, während die Funktion malloc() einen NULL-Zeiger zurückgibt.
  • Im neuen Operator müssen wir die Anzahl der zuzuweisenden Objekte angeben, während wir in der malloc()-Funktion die Anzahl der zuzuweisenden Bytes angeben müssen.
  • Im Falle eines neuen Operators müssen wir den Löschoperator verwenden, um den Speicher freizugeben. Aber im Fall der malloc()-Funktion müssen wir die free()-Funktion verwenden, um den Speicher freizugeben.

Syntax des neuen Operators

 type reference_variable = new type name; 

Wo,

Typ: Es definiert den Datentyp der Referenzvariablen.

Python rstrip

Referenzvariable: Es ist der Name der Zeigervariablen.

neu: Es handelt sich um einen Operator, der zum Zuweisen des Speichers verwendet wird.

Modellname: Es kann sich um einen beliebigen Basisdatentyp handeln.

Zum Beispiel,

Mac-Betriebssysteme
 int *p; p = new int; 

In den obigen Anweisungen deklarieren wir eine ganzzahlige Zeigervariable. Die Aussage p = neues int; reserviert den Speicherplatz für eine Integer-Variable.

Die Syntax von malloc() ist unten angegeben:

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

ptr: Es handelt sich um eine Zeigervariable.

Datentyp: Es kann sich um einen beliebigen Basisdatentyp handeln.

Zum Beispiel,

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

Die obige Anweisung reserviert den Speicher für eine ganzzahlige Variable in einem Heap und speichert dann die Adresse des reservierten Speichers in der Variablen „p“.

  • Andererseits kann der mit der Funktion malloc() zugewiesene Speicher mit der Funktion free() freigegeben werden.
  • Sobald der Speicher mit dem neuen Operator zugewiesen wurde, kann seine Größe nicht mehr geändert werden. Andererseits wird der Speicher mit der Funktion malloc() zugewiesen; Anschließend kann es mit der Funktion realloc() neu zugewiesen werden.
  • Die Ausführungszeit von new ist kürzer als die der malloc()-Funktion, da new ein Konstrukt und malloc eine Funktion ist.
  • Der neue Operator gibt nicht die separate Zeigervariable zurück; Es gibt die Adresse des neu erstellten Objekts zurück. Andererseits gibt die Funktion malloc() den void-Zeiger zurück, der weiter in einen angegebenen Typ umgewandelt werden kann.