Reputation: 414
I'm having troubles with something really silly. But I'm not been able to solve the problem. I designed a function that build a column matrix from a string resizing dynamically.
typedef struct{
double ** m_;
size_t rows_, cols_;
}matrix_t;
int loadCol(char* str, matrix_t* col){
size_t size=0; char* ptr;
if(str==NULL) return 0;
if((col=(matrix_t*)malloc(sizeof(matrix_t)))==NULL) return 0;
if((col->m_=(double**)malloc(sizeof(double*)))==NULL) return 0;
ptr = strtok(str, "|");
do{
if(((col->m_)[0]=(double*)realloc((col->m_), sizeof(double)*(size+1)))==NULL){
eraseMatrix(col);
return 0;
}
(col->m_)[0][size]=atof(ptr); /*SIGSEV*/
size++;
}while((ptr=strtok(NULL,"|"))!=NULL);
col->cols_ = 1; col->rows_ = size;
return size;
}
I debug with gdb and the problem seems to be in the assignment line mark with the comment SIGSEV. Also when the program's flow goes out from this function scope col->cols_ have incorrect data. Where is the problem in my function?
Upvotes: 0
Views: 76
Reputation: 8286
For col to be modified in a function and the modifications reflected to the caller, a pointer to col needs to be passed as matrix_t **col
. Then col has to be dereferenced in the function.
The caller would use loadCol ( str, &col);
if col is declared as matrix_t *col = NULL;
int loadCol(char* str, matrix_t** col){
size_t size=0; char* ptr;
if(str==NULL) return 0;
if((*col=(matrix_t*)malloc(sizeof(matrix_t)))==NULL) return 0;
if(((*col)->m_=(double**)malloc(sizeof(double*)))==NULL) return 0;
ptr = strtok(str, "|");
do{
if((((*col)->m_)[0]=(double*)realloc(((*col)->m_)[0], sizeof(double)*(size+1)))==NULL){
//eraseMatrix(col);
return 0;
}
((*col)->m_)[0][size]=atof(ptr);
size++;
}while((ptr=strtok(NULL,"|"))!=NULL);
(*col)->cols_ = 1; (*col)->rows_ = size;
return size;
}
strpbrk and strtod may also be used to parse values from the string.
int loadCol(char* str, matrix_t** col){
size_t size=0; char* ptr;
char *next = NULL;
if(str==NULL) return 0;
if((*col=(matrix_t*)malloc(sizeof(matrix_t)))==NULL) return 0;
if(((*col)->m_=(double**)malloc(sizeof(double*)))==NULL) return 0;
next = str;
while((ptr=strpbrk(next,"0123456789-+."))!=NULL) {
if((((*col)->m_)[0]=(double*)realloc(((*col)->m_)[0], sizeof(double)*(size+1)))==NULL){
//eraseMatrix(col);
return 0;
}
((*col)->m_)[0][size]=strtod(ptr,&next);
size++;
}
(*col)->cols_ = 1; (*col)->rows_ = size;
return size;
}
Upvotes: 1