-2

When I allocate memory in heap via calling malloc my program works(as expected). But when I dont use malloc it doesnt work. So my question is why does it make a difference when I create a struct* in call stack or heap?

struct que{
    int data[10];
    int front;
    int rear;
};

int main(){
    //struct que* q;
    struct que* q=(struct que*)malloc(sizeof(struct que));;
    q->front=-1;
    q->rear=-1;
    q->data[1]=10;
    printf("%d %d",q->rear,q->data[1]);
}
zincjello
  • 9
  • 3
  • Where is the commented out pointer pointing to? – Jose May 08 '21 at 12:56
  • You have shown a working program and asked why a different nonworking program does not work. Perhaps we are supposed to guess the nonworking program is the one obtained by commenting out the line with `malloc` and uncommenting the line with `struct que* q;`. But we do not know because you have not said. **Show the program that does not work, not the program that works.** And do not report the problem as “it doesnt work.” Describe the specific observations that indicate it does not work. Edit the question to provide a [mre]. – Eric Postpischil May 08 '21 at 13:08
  • Assuming the commented out line is the one that troubles you the reason is simple. there the variable q is declared (and allocated) as a pointer to the struct. Yet the struct itselve is not allocated. You could either do this by using malloc or you could allocate it on the stack by struct que q; – theking2 May 08 '21 at 16:08

1 Answers1

0

The definition

struct que* q;

defines q to be a pointer, but you never make it point anywhere. Its value will be indeterminate and dereferencing the pointer will lead to undefined behavior.

You probably meant to do e.g.

struct que q;

Which puts the structure object itself on the "stack".


As an aside, even with a definition like

struct que* q = malloc(sizeof(struct que));

the pointer variable q will itself be on the "stack", but the memory it points to will be on the heap.

[Note: Don't cast the result of malloc]

Also the C specification doesn't mention the use of a "stack" for local variables (including arguments), but only automatic storage. The choice to store local variable on the stack is made by the compilers and just happens to be the most common due to the architecture of CPU's.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621