so after debugging for awhile I’ve come to this in my program. It’s supposed to copy name into a circular array for a queue. I am not exactly sure what I am doing wrong here and could really use some help.
qPtr->front is an int
qPtr->numElements is an int
qPtr->queueSize is an int
name is a string
strcpy(qPtr->name[(qPtr->front+qPtr->numElements)%qPtr->queueSize], name);
here is the queue function
int enqueue(struct line* qPtr, int items, int time, char name[50])
{
int i;
if (qPtr->numElements != qPtr->queueSize)
{
qPtr->numItems[(qPtr->front+qPtr->numElements)%qPtr->queueSize] = items;
qPtr->timeEntered[(qPtr->front+qPtr->numElements)%qPtr->queueSize] = time;
strcpy(qPtr->name[(qPtr->front+qPtr->numElements)%qPtr->queueSize], name);
(qPtr->numElements)++;
}
}
I’ve determined that it isn’t when it dequeue’s because if i run the program with commenting out the line i am having issue with it runs fine. When i run the program with
strcpy(qPtr->name[(qPtr->front+qPtr->numElements)%qPtr->queueSize], name);
commented out the program runs fine. Besides that what I expect it to do is to enqueue elements from a file so that they can be dequeued later but instead it crashes
I have to ask: have you actually allocated space for the
qptr->name[]variables. If your structure is simply something like:then you will not have done so, which would lead to undefined behaviour when you try to
strcpythe name into there.Other than that, I would suggest the same thing I suggest to everyone submitting a problem.
And, temporarily, insert some
printfstatements in that function so you can see the relevant fields before and after. That will usually lead you to see exactly what’s going wrong.Based on your comments, it appears you have an array of 50 character pointers in your structure, none of which has been allocated. What you were probably aiming for was an array of character pointers, each pointing to a 50-character string.
I would suggest having your structure containing:
and change:
to:
Just remember that, when you extract that from the list, you’re responsible for freeing it when you’re done.
If you’re unlucky enough to be on a system that doesn’t have
strdup, well, here’s one I prepared earlier 🙂For what it’s worth, I dug up an old implementation from my code base, which you can use as you see fit:
Running this program generates the following debug output: