No. You still don't have it correct. I don't know what the discussion on Stack Overflow was, but the problem has nothing to do with passing a NULL pointer to the function. It has to do with passing an uninitialized pointer. You actually have two related problems. For starters, these two lines:
Variable b is a pointer. You cannot legally dereference it until you set it to point to a valid memory address (e.g. to another variable or to allocated memory). So this line is invalid:
It dereferences an uninitialized pointer, and could either poke a 0 into some random memory location or crash the program with an invalid memory access error. Both bad. This line does not set b to a NULL pointer! It dereferences the address contained in b (currently garbage) and pokes a 0 into that memory location. Bad. After this line executes, b is still uninitialized and contains garbage. Then when you get to this line:
refFunc((int)5, b); // <-- b is uninitialized
You are passing in the value of b, but b was never assigned a value. It is uninitialized and contains garbage. So that is your second problem, since refFunc dereferences b and inside the function. I.e., this line inside refFunc:
Has the same problem discussed earlier ... it dereferences an uninitialized pointer and pokes a value into a garbage memory location. You will either get bad results or crash the program.
If you really wanted to use a pointer for this line, you would need to do something like the following:
int *b;
b = (int *) mxMalloc( 1 * sizeof(*b) ); // <-- Set b to a valid value
*b = 0; // <-- Not really necessary since refFunc will set this value anyway
:
mxFree(b);
But using a pointer for this is overkill. Just pass the address of an int to your function. E.g., here is what your standalone program should look like:
#include "valFunc.h"
#include "refFunc.h"
#include <stdio.h>
void main()
{
int b; // <-- make b an int, not a pointer_to_int
printf("executing valFunc, answer is %i\n", valFunc(5));
printf("executing refFunc, ...");
refFunc(5, &b); // <-- pass the address of b into the function
printf("b is %i\n", b); // <-- simply print out b
}
And similarly, your mex code should look like this:
#include "mex.h"
#include "valFunc.h"
#include "refFunc.h"
#include <stdio.h>
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
int b;
mexPrintf("executing valFunc, answer is %i\n", valFunc(5));
mexPrintf("executing refFunc, ...");
refFunc(5, &b);
mexPrintf("b is %i\n", b);
}
The fact that you ever got results from your current code was just pure luck ... BAD luck in my opinion. It would have been better had the program crashed on you so you knew you still had a programming problem to fix.