logo

malloc() vs nuovo in C++

Entrambi i malloc() e new in C++ vengono utilizzati per lo stesso scopo. Vengono utilizzati per allocare memoria in fase di esecuzione. Ma malloc() e new hanno una sintassi diversa. La differenza principale tra malloc() e new è che new è un operatore mentre malloc() è una funzione di libreria standard predefinita in a stdlib file di intestazione.

Cosa c'è di nuovo?

Il nuovo è un operatore di allocazione della memoria, utilizzato per allocare la memoria in fase di esecuzione. La memoria inizializzata dal nuovo operatore viene allocata in un heap. Restituisce l'indirizzo iniziale della memoria, che viene assegnato alla variabile. La funzionalità dell'operatore new in C++ è simile alla funzione malloc(), utilizzata nel Linguaggio di programmazione C . C++ è compatibile anche con la funzione malloc(), ma viene utilizzato principalmente l'operatore new per i suoi vantaggi.

Sintassi dell'operatore new

 type variable = new type(parameter_list); 

Nella sintassi sopra

lista stringa java

tipo: Definisce il tipo di dati della variabile per la quale la memoria viene allocata dal nuovo operatore.

variabile: È il nome della variabile che punta alla memoria.

elenco_parametri: È l'elenco dei valori inizializzati su una variabile.

L'operatore new non utilizza l'operatore sizeof() per allocare la memoria. Inoltre non utilizza il ridimensionamento poiché l'operatore new alloca memoria sufficiente per un oggetto. È un costrutto che chiama il costruttore al momento della dichiarazione per inizializzare un oggetto.

Come sappiamo, l'operatore new alloca la memoria in un heap; se la memoria non è disponibile in un heap e il nuovo operatore tenta di allocare la memoria, viene generata l'eccezione. Se il nostro codice non è in grado di gestire l'eccezione, il programma verrà terminato in modo anomalo.

Comprendiamo l'operatore new attraverso un esempio.

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

Dove,

scan.nex java

tipo: è il tipo di dati della variabile per la quale deve essere allocata la memoria.

nome_variabile: Definisce il nome della variabile che punta alla memoria.

(tipo*): Viene utilizzato per il typecasting in modo da poter ottenere il puntatore di un tipo specificato che punta alla memoria.

taglia di(): L'operatore sizeof() viene utilizzato nella funzione malloc() per ottenere la dimensione di memoria richiesta per l'allocazione.

Nota: la funzione malloc() restituisce il puntatore void, quindi è necessario il typecasting per assegnare un tipo diverso al puntatore. L'operatore sizeof() è richiesto nella funzione malloc() poiché la funzione malloc() restituisce la memoria grezza, quindi l'operatore sizeof() dirà alla funzione malloc() quanta memoria è richiesta per l'allocazione.

Se non è disponibile memoria sufficiente, la memoria può essere ridimensionata utilizzando la funzione realloc(). Poiché sappiamo che tutti i requisiti di memoria dinamica vengono soddisfatti utilizzando la memoria heap, anche la funzione malloc() alloca la memoria in un heap e restituisce il puntatore ad essa. La memoria heap è molto limitata, quindi quando il nostro codice inizia l'esecuzione, contrassegna la memoria in uso e quando il nostro codice completa il suo compito, libera la memoria utilizzando la funzione free(). Se non è disponibile memoria sufficiente e il nostro codice tenta di accedere alla memoria, la funzione malloc() restituisce il puntatore NULL. La memoria allocata dalla funzione malloc() può essere deallocata utilizzando la funzione free().

Capiamolo attraverso un esempio.

Linux comanda quali
 #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++)>

Nel codice sopra, chiamiamo la funzione func(). La funzione func() restituisce il puntatore intero. All'interno della funzione func(), abbiamo dichiarato un puntatore *p e la memoria viene allocata a questa variabile puntatore utilizzando la funzione malloc(). In questo caso stiamo restituendo il puntatore la cui memoria è già liberata. Il ptr è un puntatore penzolante poiché punta alla posizione di memoria rilasciata. Oppure possiamo dire che ptr si riferisce a quella memoria che non è puntata dal puntatore.

Fino ad ora, impareremo a conoscere il nuovo operatore e la funzione malloc(). Ora vedremo le differenze tra l'operatore new e la funzione malloc().

Differenze tra malloc() e new

malloc() vs nuovo in C++
  • L'operatore new costruisce un oggetto, ovvero chiama il costruttore per inizializzare un oggetto while malloc() la funzione non chiama il costruttore. L'operatore new invoca il costruttore e l'operatore delete invoca il distruttore per distruggere l'oggetto. Questa è la più grande differenza tra malloc() e new.
  • Il new è un operatore, mentre malloc() è una funzione predefinita nel file di intestazione stdlib.
  • L'operatore new può essere sovraccaricato mentre la funzione malloc() non può essere sovraccaricata.
  • Se nell'heap non è disponibile memoria sufficiente, l'operatore new genererà un'eccezione mentre la funzione malloc() restituisce un puntatore NULL.
  • Nell'operatore new dobbiamo specificare il numero di oggetti da allocare mentre nella funzione malloc() dobbiamo specificare il numero di byte da allocare.
  • Nel caso di un nuovo operatore, dobbiamo utilizzare l'operatore delete per deallocare la memoria. Ma nel caso della funzione malloc(), dobbiamo usare la funzione free() per deallocare la memoria.

Sintassi dell'operatore new

 type reference_variable = new type name; 

Dove,

tipo: Definisce il tipo di dati della variabile di riferimento.

variabile_di riferimento: È il nome della variabile puntatore.

nuovo: È un operatore utilizzato per allocare la memoria.

digitare il nome: Può essere qualsiasi tipo di dati di base.

attore saira banu

Per esempio,

 int *p; p = new int; 

Nelle istruzioni precedenti, stiamo dichiarando una variabile puntatore intero. La dichiarazione p = nuovo intero; alloca lo spazio di memoria per una variabile intera.

La sintassi di malloc() è riportata di seguito:

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

ptr: È una variabile puntatore.

tipo di dati: Può essere qualsiasi tipo di dati di base.

Per esempio,

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

L'istruzione precedente allocherà la memoria per una variabile intera in un heap, quindi memorizzerà l'indirizzo della memoria riservata nella variabile 'p'.

  • D'altra parte, la memoria allocata utilizzando la funzione malloc() può essere deallocata utilizzando la funzione free().
  • Una volta allocata la memoria utilizzando l'operatore new, non è possibile ridimensionarla. D'altra parte, la memoria viene allocata utilizzando la funzione malloc(); quindi, può essere riallocato utilizzando la funzione realloc().
  • Il tempo di esecuzione di new è inferiore a quello della funzione malloc() poiché new è un costrutto e malloc è una funzione.
  • L'operatore new non restituisce la variabile puntatore separata; restituisce l'indirizzo dell'oggetto appena creato. D'altra parte, la funzione malloc() restituisce il puntatore void che può essere ulteriormente convertito in un tipo specificato.