logo

malloc () prieš naują C++

Tiek malloc () ir nauji C++ yra naudojami tam pačiam tikslui. Jie naudojami atminties paskirstymui vykdymo metu. Tačiau malloc () ir new turi skirtingą sintaksę. Pagrindinis skirtumas tarp malloc () ir new yra tas, kad naujas yra operatorius, o malloc () yra standartinė bibliotekos funkcija, kuri yra iš anksto nustatyta stdlib antraštės failą.

Kas naujo?

Naujasis yra atminties paskirstymo operatorius, kuris naudojamas atminties paskirstymui vykdymo metu. Naujojo operatoriaus inicijuota atmintis yra paskirstoma krūvoje. Jis grąžina pradinį atminties adresą, kuris priskiriamas kintamajam. Naujojo operatoriaus funkcionalumas C++ yra panašus į malloc() funkciją, kuri buvo naudojama C programavimo kalba . C++ taip pat yra suderinamas su malloc() funkcija, tačiau naujasis operatorius dažniausiai naudojamas dėl jo pranašumų.

Naujo operatoriaus sintaksė

 type variable = new type(parameter_list); 

Aukščiau pateiktoje sintaksėje

tipas: Jis apibrėžia kintamojo, kuriam atmintį skiria naujasis operatorius, duomenų tipą.

kintamasis: Tai kintamojo, kuris nurodo atmintį, pavadinimas.

Parametrų_sąrašas: Tai reikšmių, kurios inicijuojamos į kintamąjį, sąrašas.

Naujasis operatorius nenaudoja operatoriaus sizeof() atminčiai paskirstyti. Ji taip pat nenaudoja dydžio keitimo, nes naujasis operatorius skiria pakankamai atminties objektui. Tai konstrukcija, kuri deklaravimo metu iškviečia konstruktorių inicijuoti objektą.

charat java

Kaip žinome, naujasis operatorius atmintį paskirsto krūvoje; Jei atminties nėra krūvoje, o naujas operatorius bando skirti atmintį, tada išmetama išimtis. Jei mūsų kodas negali apdoroti išimties, programa bus nutraukta neįprastai.

Supraskime naująjį operatorių per pavyzdį.

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

kur,

tipas: tai kintamojo, kuriam turi būti skirta atmintis, duomenų tipas.

kintamojo_pavadinimas: Jis apibrėžia kintamojo, nukreipiančio į atmintį, pavadinimą.

(tipas*): Jis naudojamas tipo siuntimui, kad galėtume gauti nurodyto tipo žymeklį, kuris nukreipia į atmintį.

dydis(): Operatorius sizeof() naudojamas funkcijoje malloc() norint gauti paskirstymui reikalingą atminties dydį.

Pastaba: Funkcija malloc() grąžina galios žymeklį, todėl norint priskirti žymeklį kitą tipą, reikalingas tipo siuntimas. Operatorius sizeof() reikalingas funkcijoje malloc(), nes funkcija malloc() grąžina neapdorotą atmintį, taigi sizeof() operatorius nurodys funkcijai malloc() kiek atminties reikia paskirstymui.

Jei nėra pakankamai atminties, atminties dydį galima pakeisti naudojant realloc() funkciją. Kaip žinome, kad visi dinaminės atminties reikalavimai yra įvykdyti naudojant krūvos atmintį, todėl malloc() funkcija taip pat paskirsto atmintį krūvoje ir grąžina į ją žymeklį. Krūvos atmintis yra labai ribota, todėl kai mūsų kodas pradeda vykdyti, jis pažymi naudojamą atmintį, o kai mūsų kodas atlieka savo užduotį, tada atlaisvina atmintį naudodamas funkciją free(). Jei nėra pakankamai atminties, o mūsų kodas bando pasiekti atmintį, tada funkcija malloc() grąžina NULL žymeklį. Atmintis, kurią paskirsto funkcija malloc(), gali būti atlaisvinta naudojant funkciją free().

Supraskime per pavyzdį.

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

Aukščiau pateiktame kode mes vadiname funkciją func (). Funkcija func() grąžina sveikojo skaičiaus žymeklį. Funcijoje func() paskelbėme *p rodyklę, o atmintis šiam rodyklės kintamajam priskiriama naudojant funkciją malloc(). Tokiu atveju grąžiname žymeklį, kurio atmintis jau atlaisvinta. PTR yra kabantis rodyklė, nes ji rodo į išlaisvintą atminties vietą. Arba galime sakyti, kad ptr reiškia atmintį, kuri nėra nukreipta žymekliu.

Iki šiol mes sužinojome apie naują operatorių ir funkciją malloc(). Dabar pamatysime skirtumus tarp naujojo operatoriaus ir funkcijos malloc ().

Skirtumai tarp malloc() ir new

malloc () prieš naują C++
  • Naujasis operatorius sukuria objektą, t. y. jis iškviečia konstruktorių inicijuoti objektą, kol malloc () funkcija konstruktoriaus neiškviečia. Naujasis operatorius iškviečia konstruktorių, o trynimo operatorius – naikintoją, kad sunaikintų objektą. Tai yra didžiausias skirtumas tarp malloc () ir new.
  • Naujasis yra operatorius, o malloc () yra iš anksto nustatyta funkcija stdlib antraštės faile.
  • Operatorius new gali būti perkrautas, o malloc() funkcija negali būti perkrauta.
  • Jei krūvoje nėra pakankamai atminties, naujasis operatorius padarys išimtį, o funkcija malloc() grąžins NULL rodyklę.
  • Naujajame operatoriuje turime nurodyti paskirstomų objektų skaičių, o naudojant malloc() funkciją, turime nurodyti paskirstomų baitų skaičių.
  • Naujo operatoriaus atveju turime naudoti trynimo operatorių, kad išskirstytume atmintį. Tačiau malloc () funkcijos atveju turime naudoti funkciją free (), kad išskirstytume atmintį.

Naujo operatoriaus sintaksė

 type reference_variable = new type name; 

kur,

tipas: Jis apibrėžia atskaitos kintamojo duomenų tipą.

nuoroda_kintamasis: Tai žymeklio kintamojo pavadinimas.

nauja: Tai operatorius, naudojamas atminčiai paskirstyti.

tipo pavadinimas: Tai gali būti bet koks pagrindinis duomenų tipas.

Pavyzdžiui,

 int *p; p = new int; 

Aukščiau pateiktuose teiginiuose mes deklaruojame sveikojo skaičiaus rodyklės kintamąjį. Pareiškimas p = naujas int; paskirsto atminties vietą sveikajam kintamajam.

Malloc() sintaksė pateikta žemiau:

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

ptr: Tai žymeklio kintamasis.

duomenų tipas: Tai gali būti bet koks pagrindinis duomenų tipas.

Pavyzdžiui,

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

Aukščiau pateiktas teiginys paskirs atmintį sveikojo skaičiaus kintamajam krūvoje, o rezervuotos atminties adresą išsaugos kintamajame „p“.

  • Kita vertus, atmintis, skirta naudojant malloc() funkciją, gali būti atlaisvinta naudojant funkciją free().
  • Kai atmintis paskirstoma naudojant naują operatorių, jos dydžio keisti negalima. Kita vertus, atmintis paskirstoma naudojant malloc() funkciją; tada jis gali būti perskirstytas naudojant realloc() funkciją.
  • Naujo vykdymo laikas yra trumpesnis nei funkcijos malloc(), nes new yra konstrukcija, o malloc yra funkcija.
  • Naujasis operatorius nepateikia atskiro rodyklės kintamojo; jis grąžina naujai sukurto objekto adresą. Kita vertus, funkcija malloc() grąžina galios žymeklį, kurį galima toliau pateikti nurodytu tipu.