Date: Nov 21, 2012 10:50 AM
Author: Jerome
Subject: Segmentation Fault for Mex C!

When I am trying to print an element from the matrix, I get a segmentation fault. I am unsure of the issue. Any help is greatly appreciated.

example.m
function example(time,freq)

assignin('base','time',time);
assignin('base','time',freq);
mexgetputvariable;

function.c:
#include <stdio.h>
#include <string.h>
#include "mex.h"

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{

char data_name[40], time_name[40], freq_name[40];
mxArray *data_ptr, *time_ptr, *freq_ptr;
mxArray *return_val;
double *var, tvar, *fvar;

/* Check for proper number of input and output arguments */
if (nrhs !=0) {
mexErrMsgTxt("No input arguments required.");
}
if(nlhs > 1){
mexErrMsgTxt("Too many output arguments.");
}

/* Create variable for MATLAB workspace from MEX-file name. */
strcpy(data_name,"");
strcat(data_name,"data");


strcpy(time_name,"");
strcat(time_name,"time");

strcpy(freq_name,"");
strcat(freq_name,"freq");


/* Retrieve the variable from the workspace. */
data_ptr=mxCreateDoubleMatrix(621,1176,mxCOMPLEX); /* size of 1x1 (scalar) */
data_ptr = mexGetVariable("base", data_name);


time_ptr=mxCreateDoubleMatrix(621,1,mxCOMPLEX);
time_ptr = mexGetVariable("base", time_name);


freq_ptr=mxCreateDoubleMatrix(621,1,mxREAL);
freq_ptr = mexGetVariable("base", freq_name);

if (data_ptr == NULL) {
mexPrintf("Variable has not been declared in the workspace.\n");
return;
}

var=mxGetPr(data_ptr)[0];
tvar=mxGetPr(time_ptr)[0];
fvar=mxGetPr(freq_ptr)[0];


/* Display results. */
mexPrintf("Variable was declared at the command prompt as %f", fvar[0]);


mexPutVariable("base", data_name, data_ptr);
mexPutVariable("base", time_name, time_ptr);
mexPutVariable("base", time_name, freq_ptr);


mxDestroyArray(data_ptr);
}