Hello there,
I am a Java programmer by trade and am VERY new to C so please excuse any blatant pointer ignorance, if possible. I am having a problem with the concept of returning something but also freeing it afterwards within a method.
I am implementing a stack program and for pop, I want it to return the name of the just-popped item but also free the struct that name lives in. The code is below- it will better illustrate what I am trying to say.
#define STACK_NAME_SIZE 100
struct StackElement {
char name[STACK_NAME_SIZE];
struct StackElement *next;
};struct StackElement *stackTop = 0;
void push (char* aName) {
struct StackElement* e = (struct StackElement*) malloc (sizeof (struct StackElement));
strncpy (e->name, aName, STACK_NAME_SIZE);
e->next = stackTop;
stackTop = e;
}
char* pop () {
struct StackElement *e = stackTop;
stackTop = e->next;
char name1[STACK_NAME_SIZE];
strcpy(name1,e->name);
free (e);
return *name1;
}
As it stands now, I am getting a segfault. I think the problem is because I am not using malloc to initialize name1...? However, I really really want to avoid using malloc if possible because I have no opportunity to free name1 later (since we are given a bunch of test suites that we cannot alter). Ideally, I would like name1 to somehow be a local variable that the compiler will clean up after I return the name value.
I apologize if strcpy is not the right way to do it... I have tried straight assignment, char*s instead of char[]s, strncpy.... everything. I am at a loss. I would love any and all input (though it is a school assignment so I am not asking for a solution in code ready made, of course... I'd really like to understand my mistake).
Thank you!
-Shrublet