Skip to content

techtrendings.com

Let's explore

Menu
Menu

Difference between new and malloc

Posted on January 5, 2022January 5, 2022 by Avidlearner

malloc() returns a void pointer it is necessary to explicitly typecast it into an appropriate type of pointer.

This gets completely avoided when using new operator. E.g

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

float *ptr2 = (float *)malloc(sizeof(float));

ExampleClass *ptr3 = (ExampleClass*)malloc(sizeof(sample));

Here ExampleClass is a user defined class.

int *ptr1 = new int;

int *ptr2 = new int;

ExampleClass *ptr3 = new ExampleClass;

new automatically calls the constructor while malloc does not.

new returns a fully typed pointer while malloc returns a void*.

new being an operator can be overloaded while malloc cannot

Related

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Implement Trie Data Structure in C++- LeetCode
  • How TLS Works
  • C++ – Factory Design Pattern – Creation Design Pattern
  • C++ – Strategy Design Pattern – Behavioral Design Pattern
  • LFU Cache Implementation – LeetCode

Recent Comments

  • automatically like friends photos on instagram on Program to find unpaired element in an Array in C++|Leetcode |techtrendings
  • Twicsy on Program to find unpaired element in an Array in C++|Leetcode |techtrendings

Archives

  • January 2023
  • November 2022
  • August 2022
  • June 2022
  • May 2022
  • March 2022
  • February 2022
  • January 2022

Categories

  • Algorithm
  • Algorithm
  • C++
  • Design Patterns
  • Multithreading
  • OS Concepts
  • Programming
  • Uncategorized

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Join Our Mailing List for the Latest News and Updates.

© 2023 techtrendings.com | Powered by Superbs Personal Blog theme