Question

What is the difference bettween this line of code in C++: students = (Student *)malloc(capacity *...

What is the difference bettween this line of code in C++:

students = (Student *)malloc(capacity * sizeof(Student));

and this line of code:

Student* students = new Student[capacity];

?

When I try to run the 2nd version, my IDE's debugger would tell me: "Signal received: SIGSEGV (Segmentation fault)
For program cse330_1_10, pid 21,112"
and the program would crash; however, it wouldn't crash for the first line of code above.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

`Hey,

Note: Brother in case of any queries, just comment in box I would be very happy to assist all your queries

Both are used for same purpose, but still they have some differences, the differences are:

  1. new is an operator whereas malloc() is a library function.
  2. new allocates memory and calls constructor for object initialization. But malloc() allocates memory and does not call constructor.
  3. Return type of new is exact data type while malloc() returns void*.
  4. new is faster than malloc() because an operator is always faster than a function.

The below program works fine in my IDE and I have tried it online too.

#include<iostream>

#include<stdlib.h>

using namespace std;
struct Student
{
int name;
};
int main()
{
Student* students = (Student *)malloc(10 * sizeof(Student));

Student* students1 = new Student[10];

}

Kindly revert for any queries

Thanks.

Add a comment
Know the answer?
Add Answer to:
What is the difference bettween this line of code in C++: students = (Student *)malloc(capacity *...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT