Does C allocate memory automatically for me?

前端 未结 8 2135
情话喂你
情话喂你 2020-12-19 14:18

I have been writing C for only a scant few weeks and have not taken the time to worry myself too much about malloc(). Recently, though, a program of mine return

8条回答
  •  别那么骄傲
    2020-12-19 14:52

    Local variables are "allocated" on the stack. The stack is a preallocated amount of memory to hold those local variables. The variables cease to be valid when the function exits and will be overwritten by whatever comes next.

    In your case, the code is doing nothing since it doesn't return your result. Also, a pointer to an object on the stack will also cease to be valid when the scope exits, so I guess in your precise case (you seems to be doing a linked list), you will need to use malloc().

提交回复
热议问题