Malloc function (dynamic memory allocation) resulting in an error when it is used globally

You can’t execute code outside of functions. The only thing you can do at global scope is declaring variables (and initialize them with compile-time constants).

malloc is a function call, so that’s invalid outside a function.

If you initialize a global pointer variable with malloc from your main (or any other function really), it will be available to all other functions where that variable is in scope (in your example, all functions within the file that contains main).

(Note that global variables should be avoided when possible.)

Leave a Comment