Jump to content


A compilation error about malloc


5 replies to this topic

#1 kotiloli

    New Member

  • Members
  • Pip
  • 2 posts

Posted 14 June 2009 - 08:16 PM

#include<stdio.h>
#include<stdlib.h>
  struct node{
     int data;
     struct node *nextNode;
     };
 int main(){
     struct node node1,*nptr;
     node1.data=10;
     node1.nextNode=NULL;
     nptr=&node1;
     nptr= malloc(sizeof(struct node));
     nptr->data=100;
     nptr->nextNode=&node1;

    return 0;
}
When I compile this part of code in my computer I get this error:(I use DEV C++)
>>>> ERROR: invalid conversion from´void*' to ´node*'

but when I compiled it in my friend compiler(DEV C++) , it works seamlessly.

I WANT TO KNOW WHAT MY COMPILER PROBLEM IS?

#2 Reedbeta

    DevMaster Staff

  • Administrators
  • 5310 posts
  • LocationSanta Clara, CA

Posted 14 June 2009 - 08:58 PM

First, please use [code]...[/code] when posting code.

Second, please indicate what line of the program is giving the error. I'm going to guess that it is the line calling malloc().

The solution is to use a type cast: nptr = (node *)malloc(sizeof(struct node)). This instructs the compiler to treat the output of malloc as a node * even though it's really a void *.

The reason the compiler doesn't do this automatically is because technically it is not type-safe. A void * can point to any data at all, which may or may not be a 'node' struct, so it is not safe to treat it as a node *.

Whatever compiler your friend is using may let you get away with this specifically for malloc() as a special case, for convenience, but you shouldn't rely on this behavior. (Note: DevC++ is the IDE, not the compiler.)
reedbeta.com - developer blog, OpenGL demos, and other projects

#3 kotiloli

    New Member

  • Members
  • Pip
  • 2 posts

Posted 15 June 2009 - 08:22 AM

thans for your guide.

#4 Trap D

    Member

  • Members
  • PipPip
  • 55 posts

Posted 15 June 2009 - 09:41 AM

If you use a C compiler (you have a file xxx.c) you have no error, but with a C++ compiler (you have a file xxx.cpp) you have an error.

#5 .oisyn

    DevMaster Staff

  • Moderators
  • 1842 posts

Posted 15 June 2009 - 03:08 PM

Yup, this is typical C code (with the 'struct node variable' definitions and malloc()). C allows implicit casts from void* to T*, but C++ doesn't. You obviously try to compile the code with the compiler in C++ mode, while your friend is compiling it in C mode.
C++ addict
-
Currently working on: the 3D engine for Tomb Raider.

#6 monjardin

    Senior Member

  • Members
  • PipPipPipPip
  • 1033 posts

Posted 16 June 2009 - 02:12 AM

These cast would be a pain in C since void* is the only way to approach the flexibility of templates.
monjardin's JwN Meter (1,2,3,4,5,6):
|----|----|----|----|----|----|----|----|----|----|
*





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users