How is the array stored in memory?

An array stores its elements in contiguous memory locations. If You created the array locally it will be on stack. Where the elements are stored depends on the storage specification. For Example: An array declared globally or statically would have different storage specification from an array declared locally. Technically, the where part is implementation defined … Read more

Where in memory are string literals ? stack / heap? [duplicate]

The string literal will be allocated in data segment. The pointer to it, a, will be allocated on the stack. Your code will eventually get transformed by the compiler into something like this: #include <stdio.h> const static char literal_constant_34562[7] = {‘t’, ‘e’, ‘s’, ‘a’, ‘j’, ‘a’, ‘\0’}; int main() { char *a; a = &literal_constant_34562[0]; … Read more

Stack vs heap allocation of structs in Go, and how they relate to garbage collection

It’s worth noting that the words “stack” and “heap” do not appear anywhere in the language spec. Your question is worded with “…is declared on the stack,” and “…declared on the heap,” but note that Go declaration syntax says nothing about stack or heap. That technically makes the answer to all of your questions implementation … Read more

Why would you ever want to allocate memory on the heap rather than the stack? [duplicate]

There are a few reasons: The main one is that with heap allocation, you have the most flexible control over the object’s lifetime (from malloc/calloc to free); Stack space is typically a more limited resource than heap space, at least in default configurations; A failure to allocate heap space can be handled gracefully, whereas running … Read more