Wrote your sheet on c. But at the end of the program crashes with the error: Run-Time Check Failure # 2 Stack around the variable "l" was corrupted.

main.c:

#include "objects.h" int main() { list l; init_list(&l); return 0; } 

object.c:

 #include <stdio.h> #include <stdlib.h> typedef struct _comp { struct _comp *next; struct _comp *prev; } comp; typedef struct _list { comp *first; comp *tail; } *list; void init_list(list l) { comp *first = (comp*)malloc(sizeof(comp)); if (first == NULL) { fprintf(stderr, "failed to allocate memory.\n"); exit(-1); } comp *last = (comp*)malloc(sizeof(comp)); if (last == NULL) { fprintf(stderr, "failed to allocate memory.\n"); exit(-1); } first->prev = NULL; last->next = NULL; first->next = last; last->prev = first; l->first = first; l->tail = last; } 

objects.h

 typedef struct _list *list; void init_list(list l); 
  • For starters - you are not mistaken anywhere? void init_list(list l); and list l; init_list(&l); list l; init_list(&l); ? Is that how you work? - Harry
  • @Harry, this is exactly the way the code is written, because init_list (l) does not work at all (the uninitialized local variable "l" is used). I had a similar trick before. I'm more interested in why the program crashes at the very end, when all functions are completed. - nikiquark
  • There is no point in discussing the launch of a program that does not even compile. The compiler issued you a standard diagnostic message. There is nothing to talk about. - AnT

1 answer 1

A very unhealthy occupation - tying the wheel to the car with ropes, if the bolt does not go there - this is to your

because init_list (l) does not work at all (the uninitialized local variable "l" is used)

So why didn't you initialize it? It was thought that the right bolt is a luxury, let's get rid of the rope?

You did not allocate memory, respectively, here

 l->first = first; l->tail = last; 

spoiled the stack.

The scraps swept under the rug — so that no one sees — they begin to stink ...

Let's do the cleaning.

 list l = malloc(sizeof(*list)); init_list(l);