c - Weird malloc behaviour -


i have encountered weird malloc behaviour , hopping can shed light on it.

here 1 function:

struct flownetwork * creategraph(){     struct flownetwork * fn = initflownetwork();     insertadjmatrix(fn->adjmatrix, 0, 3, 0, 10);     insertadjmatrix(fn->adjmatrix, 0, 2, 0, 12);     insertadjmatrix(fn->adjmatrix, 0, 1, 0, 5);     insertadjmatrix(fn->adjmatrix, 1, 4, 0, 6);     insertadjmatrix(fn->adjmatrix, 2, 5, 0, 11);     insertadjmatrix(fn->adjmatrix, 4, 5, 0, 5);     insertadjmatrix(fn->adjmatrix, 3, 5, 0, 5);     insertadjmatrix(fn->adjmatrix, 3, 7, 0, 5);     insertadjmatrix(fn->adjmatrix, 4, 5, 0, 5);     insertadjmatrix(fn->adjmatrix, 5, 7, 0, 10);     insertadjmatrix(fn->adjmatrix, 5, 6, 0, 8);     insertadjmatrix(fn->adjmatrix, 7, 8, 0, 16);     insertadjmatrix(fn->adjmatrix, 6, 8, 0, 9);     return fn; } 

notice second line calls function return pointer flownetwork struct. here code fuction:

struct flownetwork *  initflownetwork(){      struct flownetwork * n = (struct flownetwork *)malloc(sizeof(struct flownetwork));      n->adjmatrix = initadjmatrix();      int i;      (i = 0; < nodes; i++)      {         n->visitednodes[i] = 0;         n->parent[i] = -1;      } } 

notice never returned pointer (i forgot add , noticed later). despite not having return code work if did have return pointer statement.
know why works?

does know why works?

pure luck. in fact, c says "forgetting" return statement in function non-void return type results in undefined behaviour, i.e. might happen, program might crash, house might burn down, compiler might start own instance of skynet...

the point here compiler means of being nice. think shouldn't. try compiling -wall, see lot more warnings.

on x86, won't happen accidentially. return value typically stored in cpu register %eax, , if don't explicitely return pointer, there's no reason should in register. however, last 1 write %eax in function malloc, , since return value of malloc, address of newly allocated space, same return value want produce, namely address of new flownetwork happens work. shudder!

edit clearer: mean "the compiler nice" not scream face, telling you've made terrible mistake, not it's magically return right value.


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -