strdup(.)
recommended by other answers is non-standard. If you're not on a Unix platform it may not be available.
However the point is correct. You need to allocate memory to store your string.
Try:
const size_t sz=(strlen(string)+1)*sizeof(*string);//Space required. Including '\0' terminator.
new->text=malloc(sz);//space allocated.
if(new->text==NULL){//sz never 0 because +1.
exit(EXIT_FAILURE);//Allocation failed in non-error handled function.
}
memcpy(new->text,string,sz); //typically fastest way to copy!
Instead of strdup(.)
.
My use of sizeof(*string)
is actually unnecessary (as it is always 1) but the compiler will spot that and it's just good practice.
One day the world will move more uniformly to multi-byte characters and this code is ready for that glorious dawn!
Don't forget to free(.)
when you've finished with the 'QElement'.
You should probably write a function like this:
void QElementDestroy(QElement*const element){
if(element==NULL){
return;//Nothing to do!
}
free(element->text);//Needs NULL protection.
free(element);//Does not need NULL protection. But we've done the test anyway!
//NB: Order matters here. A lot.
}
And call it when you've finished with value returned by enqueue(.)
.
If you want the string to 'out live' the element set element->text=NULL
before calling destroy.
free(NULL)
is required to do nothing and return normally.
PS: I think strdup(.)
is a bit of a n00b trap. They take a while to get the hang of matching malloc(.)
and free(.)
and strdup(.)
is a bit of a traitor because none of the other str...
functions allocate space the caller is expected to free(.)
. It's also non-standard.