Given the struct below, I am creating a function that takes in a person_in_queue
and a position_num
and allocating a new queue_t
struct that is added to the end of a list of queue_t
structs as specified by the first argument.
typedef struct queue {
int position_num;
char *person_in_queue;
struct queue *next_in_line;
} queue_t;
I have written my code as such:
queue_t *add_to_queue(queue_t *input_queue, char *person_in_queue, int position_num) {
input_queue = malloc(sizeof(queue_t));
assert(input_queue != NULL);
input_queue->position_num = position_num;
input_queue->person_in_queue = (char *) malloc((strlen(new_text) + 1) * sizeof(char));
assert(input_queue->person_in_queue != NULL);
strcpy(input_queue->person_in_queue, person_in_queue);
return input_queue;
}
Said code compiles, however, I am told that my code fails given that less memory is allocated than what is expected. At the moment, I'm not sure where I am going wrong here. Do note that I need to use malloc()
!
Many thanks!
sizeof
is an operator in C, not a funciton, but parenthesis are necessary to evaluate types.
To allocate memory for the struct, use the size of the type.
input_queue = malloc(sizeof (queue_t));
Or use the de-referenced pointer or object size (parenthesis not necessary here).
input_queue = malloc(sizeof *input_queue);
I am told that my code fails given that less memory is allocated than what is expected.
That must refer to the malloc((strlen(new_text) + 1) * sizeof(char))
. Apparently new_text
is a global string with no visible connection to person_in_queue
, which latter is to be duplicated. Change the call to malloc(strlen(person_in_queue) + 1)
.
How to properly allocate enough memory (malloc) when creating a new struct in C?
Apart from the above, the allocation is basically okay, but as Marco Bonelli noted, you're taking input_queue as argument and immediately overwriting it … That doesn't make much sense … It would rather make sense to return the allocated queue_t
object if input_queue
is initially NULL
, otherwise the passed input_queue
unchanged. This can be accomplished by changing the first two statements of your function's body to
queue_t *head_queue = input_queue, **pr = &input_queue;
while (*pr) pr = &(*pr)->next_in_line; // find end of list
*pr = // link new struct to list
input_queue = malloc(sizeof(queue_t));
assert(input_queue != NULL);
input_queue->next_in_line = NULL; // don't forget to initialize!
and the return statement to
return head_queue ? head_queue : input_queue;
- the former also sets the link pointers next_in_line
correctly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.