i have a serious problem with this malloc function used in C language.i have been studying the topic "new" for few days,and there i found a code in which malloc was used.i am trying to change it to new but my compiler always always CRASHES.

the line which i think crashes my compiler is:-

r->next=(class polynomial *)malloc(sizeof(class polynomial))

if somebody wants the program which put me in trouble,please do ask for it.

please please help me im in a big trouble.

Recommended Answers

All 4 Replies

i have a serious problem with this malloc function used in C language.i have been studying the topic "new" for few days,and there i found a code in which malloc was used.i am trying to change it to new but my compiler always always CRASHES.

the line which i think crashes my compiler is:-

r->next=(class polynomial *)malloc(sizeof(class polynomial))

if somebody wants the program which put me in trouble,please do ask for it.

please please help me im in a big trouble.

First is (class polynomial *) even correct? Shouldn't it just be (polynomial*)? If it is possible to do it your "class" way, then nevermind this part.

malloc should only be used for primitive types that do not require a constructor because malloc will not call the constructor. So even though that code may compile, it will not use your constructor that you have specified in your polynomial class. Therefore your program may crash because your constructor is necessary for your program to function properly.

You definitely should use the "new" operator, because "new" calls the constructor during allocation. The correct syntax would be:

r->next = new polynomial;

I don't ever use malloc() in a c++ program, its just too confusing to mix malloc() and new together in the same c++ program. Stick with new for consistency and to be less error prone.

Are you sure it's your *compiler* that's crashing? Or is your program crashing during execution? If it's the latter, it's more than likely that "r" is pointing to invalid memory or "r" is a NULL pointer.

the error was with the "malloc",i finally changed it to "new" with some changes in my code too.well thanks everyone for your help, appreciate it :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.