Reputation: 11
I have a following problem in which I can't figure out how to assign a char*
called funcName
to a char*
called fname
. Need some help, thanks.
#define MAX_PARMS 5
typedef enum {C_INT, C_SHORT, C_CHAR, C_FLOAT, C_INT_PTR} DataType;
typedef struct {
char name;
int *value;
DataType dType;
} VarType;
typedef struct {
char *funcName;
VarType parms[MAX_PARMS];
int numParms;
} FrameType;
void enterSumFunc (StackType *stkPtr, char *fname, int num, int *arr, int *sum) {
FrameType *temp;
//temp->funcName = fname;
strcpy(temp->funcName, fname);
}
As you can see I have tried both strcpy
and manually setting the char*
but nothing works; both give a segmentation fault. Any help will be useful, thanks.
Upvotes: 0
Views: 148
Reputation: 29265
temp
is not set, so dereferencing it (->
) will never be valid.
Based on edited code (specifying FrameType
)
FrameType *temp = malloc(sizeof(FrameType));
temp->funcName = fname;
or
FrameType obj;
FrameType *temp = &obj;
temp->funcName = fname;
Will "work", but it's a "shallow copy" of data. If the "owner" of fname
deletes it or changes it, then your temp
object becomes invalid. You can either use strdup()
to copy the name, or put a char[]
in the FrameType
instead of just a pointer.
If temp
really is a temp (and doesn't have to live past the end of the function call) then the second approach is probably better.
Remember for each malloc
you need a free
or elase you will leak memory. The second approach shown above reduces that risk...
Upvotes: 1
Reputation: 42083
FrameType *temp;
temp->funcName ...
dereferences an uninitialized pointer, which yields undefined behavior, which in this case you are able to observe as segmentation fault. One of the possible solutions is using an object with automatic storage duration instead of pointer:
FrameType temp;
temp.funcName ...
Also note that
temp->funcName = fname;
assigns the value of pointer fname
(i.e. an address it points to) to the pointer funcName
, no copying is performed and once the memory associated with fname
is freed, this temp->funcName
will be an invalid (dangling) pointer and using it will also result in undefined behavior.
On the other hand:
strcpy(temp->funcName, fname);
tries to copy null-terminated string stored in fname
to funcName
and in case the string is not null terminated or there is no memory associated with this pointer, it will result in undefined behavior as well.
Note that:
typedef struct {
char *funcName;
VarType parms[MAX_PARMS];
int numParms;
} FrameType;
only declares a pointer funcName
so you should either explicitly allocate a memory using malloc
before trying to copy a string to it or yet even better, use a buffer with automatic storage duration instead:
typedef struct {
char funcName[255];
VarType parms[MAX_PARMS];
int numParms;
} FrameType;
Upvotes: 1