Okay so here is the gist of what's happening:
I am passing in a character array (char[x])
into a function, whose argument is defined to be a character pointer (char *)
. Once inside the function I assign another character pointer (which is a part of a struct I have). I get a segmentation fault as soon as I assign the incoming argument, to the structure's character pointer; as such.
temp->name = (char*)malloc(sizeof(char));
temp->name = name;
This is how I've been utilizing the function previously:
char *name = "HEY";
Function(name);
Here's how I am utilizing it with errors:
char name[3] = "HEY";
Function(name);
with the same statement above, and it works fine. I made sure it wasn't anything else, by changing name to a constant "HEY", with the same input and everything went smoothly.
If anybody can think of a reason why off the top of their head, I would greatly appreciate the help. Thank you!
Here's the function in full:
- openList is the pointer to the beginning of a linked list of structs
- tempOpen is a temporary pointer we can utilize to scour through the list, without altering the openList position
- findOpenSetSID/findItem -> looks for a struct in the linked list via the SID/key
- answerOpen/answerItem -> 1 == first node, 2 == any other node, 0 = not found
Here is a breif summary of the structures involved. The open structure is a linked list of pointers to another structure (called set structures) A set structure is a linked list of names, sid's, and a item structure An item structure is a linked list of data and keys
Error_t WRITE(Sid_t sid, char *key, char *data){
Open_p_t tempOpen = openList; //setting a pointer to a struct
int answerOpen = findOpenSetSID(sid, &tempOpen);
if(answerOpen > 0){
Set_p_t targetNode;
if(answerOpen == 1){
targetNode = tempOpen->file;
}
else{
targetNode= tempOpen->next->file;
}
Item_p_t tempItem = targetNode->items;
int answerItem = findItem(key, &tempItem);
Item_p_t targetItem;
targetItem = (Item_p_t)malloc(sizeof(Item_t));
if(answerItem > 0){
if(answerItem == 1){
targetItem = targetNode->items;
}
else{
targetItem = targetNode->items->next;
}
targetItem->data = data;
}
else{
**targetItem->data = data;** <<<The problem line.
basically I am just adding
items to my sets. But this line
freaks out when the input changes
from char* to char[]
targetItem->key = key;
targetItem->next = targetNode->items;
targetNode->items = targetItem;
}
return 0;
}
return 1;
}
Here's the input segment:
char key[32], data[64]; // reads in data using fscanf(fd, "%s %s", key data)
then calls WRITE(setId, key, data);