I write a 'constructor' function that makes a Node in C, compiled with Visual Studio 2008, ANSI C mode.
#include <stdio.h>
#include <stdlib.h>
typedef struct _node
{
struct _node* next ;
char* data ;
} Node ;
Node * makeNode()
{
Node * newNode = (Node*)malloc( sizeof(Node) ) ;
// uncommenting this causes the program to fail.
//puts( "I DIDN'T RETURN ANYTHING!!" ) ;
}
int main()
{
Node * myNode = makeNode() ;
myNode->data = "Hello there" ;
// elaborate program, still works
puts( myNode->data ) ;
return 0 ;
}
What's surprising to me :
- * Not returning a value from makeNode() is only a warning,
- * More surprising is makeNode() __still works__ as long as I don't puts() anything!
What's going on here and is it "ok" to do this (not return the object you create in a C 'constructor' function?)
WHY is it still working? Why does the puts() command cause the program to fail?