Oba malloc() in new v C++ se uporabljajo za isti namen. Uporabljajo se za dodeljevanje pomnilnika med izvajanjem. Toda malloc() in new imata različno sintakso. Glavna razlika med malloc() in new je, da je new operator, medtem ko je malloc() standardna knjižnična funkcija, ki je vnaprej določena v stdlib naslovna datoteka.
Kaj je novega?
Novost je operator za dodeljevanje pomnilnika, ki se uporablja za dodeljevanje pomnilnika med izvajanjem. Pomnilnik, ki ga je inicializiral operater new, je dodeljen na kupu. Vrne začetni naslov pomnilnika, ki se dodeli spremenljivki. Funkcionalnost novega operatorja v C++ je podobna funkciji malloc(), ki je bila uporabljena v Programski jezik C . C++ je združljiv tudi s funkcijo malloc(), vendar se zaradi svojih prednosti večinoma uporablja operator new.
Sintaksa operatorja new
type variable = new type(parameter_list);
V zgornji sintaksi
vrsta: Določa podatkovni tip spremenljivke, za katero je dodeljen pomnilnik z new operatorjem.
spremenljivka: To je ime spremenljivke, ki kaže na pomnilnik.
zamenjava java niza
seznam_parametrov: To je seznam vrednosti, ki so inicializirane za spremenljivko.
Operator new ne uporablja operatorja sizeof() za dodelitev pomnilnika. Prav tako ne uporablja spreminjanja velikosti, saj operator new dodeli dovolj pomnilnika za objekt. To je konstrukt, ki v času deklaracije pokliče konstruktor, da inicializira objekt.
Kot vemo, operater new dodeli pomnilnik v kopici; če pomnilnik ni na voljo v kupu in novi operater poskuša dodeliti pomnilnik, se vrže izjema. Če naša koda ne more obravnavati izjeme, bo program nenormalno prekinjen.
Razumejmo nov operater na primeru.
#include using namespace std; int main() { int *ptr; // integer pointer variable declaration ptr=new int; // allocating memory to the pointer variable ptr. std::cout << 'Enter the number : ' <>*ptr; std::cout << 'Entered number is ' <<*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's understand through an example.</strong> </p> <pre> #include #include using namespace std; int main() { int len; // variable declaration std::cout << 'Enter the count of numbers :' <> 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 << 'Entered elements are : ' << 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'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 'p' 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<<>
kje,
vrsta: je podatkovni tip spremenljivke, za katero je treba dodeliti pomnilnik.
ime_spremenljivke: Določa ime spremenljivke, ki kaže na pomnilnik.
(tip*): Uporablja se za pretvorbo tipov, tako da lahko dobimo kazalec določene vrste, ki kaže na pomnilnik.
sizeof(): Operator sizeof() se uporablja v funkciji malloc() za pridobitev velikosti pomnilnika, potrebne za dodelitev.
Opomba: funkcija malloc() vrne prazen kazalec, zato je za dodelitev drugega tipa kazalcu potrebno prevajanje tipov. Operator sizeof() je potreben v funkciji malloc(), saj funkcija malloc() vrne neobdelani pomnilnik, zato bo operator sizeof() funkciji malloc() povedal, koliko pomnilnika je potrebno za dodelitev.
Če ni na voljo dovolj pomnilnika, lahko velikost pomnilnika spremenite s funkcijo realloc(). Ker vemo, da so vse zahteve glede dinamičnega pomnilnika izpolnjene s pomnilnikom kopice, zato funkcija malloc() tudi dodeli pomnilnik v kopici in vrne kazalec nanj. Pomnilnik kopice je zelo omejen, zato naša koda, ko se začne izvajati, označi pomnilnik v uporabi, in ko naša koda dokonča svojo nalogo, sprosti pomnilnik s funkcijo free(). Če ni na voljo dovolj pomnilnika in naša koda poskuša dostopati do pomnilnika, potem funkcija malloc() vrne kazalec NULL. Pomnilnik, ki ga dodeli funkcija malloc(), lahko sprostite s funkcijo free().
Razumejmo skozi primer.
kako pretvoriti niz v celo število java
#include #include using namespace std; int main() { int len; // variable declaration std::cout << 'Enter the count of numbers :' <> 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 << 'Entered elements are : ' << 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'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 'p' 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++)>
V zgornji kodi kličemo funkcijo func(). Funkcija func() vrne celoštevilski kazalec. Znotraj funkcije func() smo deklarirali kazalec *p in pomnilnik je tej spremenljivki kazalca dodeljen s funkcijo malloc(). V tem primeru vrnemo kazalec, katerega pomnilnik je že sproščen. PTR je viseči kazalec, saj kaže na sproščeno pomnilniško lokacijo. Lahko pa rečemo, da se ptr nanaša na tisti pomnilnik, na katerega ne kaže kazalec.
Do sedaj smo se seznanili z novim operatorjem in funkcijo malloc(). Zdaj bomo videli razlike med operatorjem new in funkcijo malloc().
Razlike med malloc() in new
- Operator new konstruira objekt, tj. pokliče konstruktor, da inicializira objekt while malloc() funkcija ne kliče konstruktorja. Operator new prikliče konstruktor, operator delete pa destruktor, da uniči objekt. To je največja razlika med malloc() in new.
- New je operator, medtem ko je malloc() vnaprej določena funkcija v datoteki glave stdlib.
- Operator new je lahko preobremenjen, medtem ko funkcije malloc() ni mogoče preobremeniti.
- Če v kupu ni na voljo dovolj pomnilnika, bo operator new vrgel izjemo, medtem ko funkcija malloc() vrne kazalec NULL.
- V novem operaterju moramo določiti število predmetov, ki jih bomo dodelili, medtem ko moramo v funkciji malloc() določiti število bajtov, ki jih bomo dodelili.
- V primeru novega operatorja moramo za sprostitev pomnilnika uporabiti operator delete. Toda v primeru funkcije malloc() moramo za sprostitev pomnilnika uporabiti funkcijo free().
Sintaksa operatorja new
type reference_variable = new type name;
kje,
vrsta: Določa podatkovni tip referenčne spremenljivke.
referenčna_spremenljivka: To je ime spremenljivke kazalca.
novo: Je operater, ki se uporablja za dodeljevanje pomnilnika.
vnesite ime: Lahko je kateri koli osnovni podatkovni tip.
na primer
int *p; p = new int;
V zgornjih izjavah deklariramo spremenljivko kazalca celo število. Izjava p = novo int; dodeli pomnilniški prostor celoštevilski spremenljivki.
Sintaksa malloc() je podana spodaj:
int *ptr = (data_type*) malloc(sizeof(data_type));
ptr: To je spremenljivka kazalca.
data_type: Lahko je kateri koli osnovni podatkovni tip.
na primer
int *p; p = (int *) malloc(sizeof(int))
Zgornji stavek bo dodelil pomnilnik za celoštevilsko spremenljivko v kopici in nato shranil naslov rezerviranega pomnilnika v spremenljivki 'p'.
- Po drugi strani pa lahko pomnilnik, dodeljen s funkcijo malloc(), sprostite s funkcijo free().
- Ko je pomnilnik dodeljen z uporabo novega operaterja, mu ni več mogoče spremeniti velikosti. Po drugi strani pa se pomnilnik dodeli s funkcijo malloc(); potem ga je mogoče prerazporediti s funkcijo realloc().
- Čas izvajanja new je krajši od časa malloc(), saj je new konstrukt, malloc pa funkcija.
- Operator new ne vrne ločene spremenljivke kazalca; vrne naslov novo ustvarjenega objekta. Po drugi strani pa funkcija malloc() vrne prazen kazalec, ki ga je mogoče nadalje preoblikovati v določen tip.
*ptr<<>