<p>I've always heard that in C you have to really watch how you manage memory. And I'm still beginning to learn C, but thus far, I have not had to do any memory managing related activities at all.. I always imagined having to release variables and do all sorts of ugly things. But this doesn't seem to be the case.</p>

<p>Can someone show me (with code examples) an example of when you would have to do some "memory management" ?</p>

[{'answer_id': 24893, 'author': 'Paige Ruten', 'author_id': 813, 'author_profile': 'https://Stackoverflow.com/users/813', 'pm_score': 3, 'selected': False, 'text': '<p>You have to do "memory management" when you want to use memory on the heap rather than the stack. If you don\'t know how large to make an array until runtime, then you have to use the heap. For example, you might want to store something in a string, but don\'t know how large its contents will be until the program is run. In that case you\'d write something like this:</p>\n\n<pre><code> char *string = malloc(stringlength); // stringlength is the number of bytes to allocate\n\n // Do something with the string...\n\n free(string); // Free the allocated memory\n</code></pre>\n'}, {'answer_id': 24895, 'author': 'TheSmurf', 'author_id': 1975282, 'author_profile': 'https://Stackoverflow.com/users/1975282', 'pm_score': -1, 'selected': False, 'text': "<p>Sure. If you create an object that exists outside of the scope you use it in. Here is a contrived example (bear in mind my syntax will be off; my C is rusty, but this example will still illustrate the concept):</p>\n\n<pre><code>class MyClass\n{\n   SomeOtherClass *myObject;\n\n   public MyClass()\n   {\n      //The object is created when the class is constructed\n      myObject = (SomeOtherClass*)malloc(sizeof(myObject));\n   }\n\n   public ~MyClass()\n   {\n      //The class is destructed\n      //If you don't free the object here, you leak memory\n      free(myObject);\n   }\n\n   public void SomeMemberFunction()\n   {\n      //Some use of the object\n      myObject-&gt;SomeOperation();\n   }\n\n\n};\n</code></pre>\n\n<p>In this example, I'm using an object of type SomeOtherClass during the lifetime of MyClass. The SomeOtherClass object is used in several functions, so I've dynamically allocated the memory: the SomeOtherClass object is created when MyClass is created, used several times over the life of the object, and then freed once MyClass is freed.</p>\n\n<p>Obviously if this were real code, there would be no reason (aside from possibly stack memory consumption) to create myObject in this way, but this type of object creation/destruction becomes useful when you have a lot of objects, and want to finely control when they are created and destroyed (so that your application doesn't suck up 1GB of RAM for its entire lifetime, for example), and in a Windowed environment, this is pretty much mandatory, as objects that you create (buttons, say), need to exist well outside of any particular function's (or even class') scope.</p>\n"}, {'answer_id': 24908, 'author': 'Mark Harrison', 'author_id': 116, 'author_profile': 'https://Stackoverflow.com/users/116', 'pm_score': 4, 'selected': False, 'text': '<p>Here\'s an example.  Suppose you have a strdup() function that duplicates a string:</p>\n\n<pre><code>char *strdup(char *src)\n{\n    char * dest;\n    dest = malloc(strlen(src) + 1);\n    if (dest == NULL)\n        abort();\n    strcpy(dest, src);\n    return dest;\n}\n</code></pre>\n\n<p>And you call it like this:</p>\n\n<pre><code>main()\n{\n    char *s;\n    s = strdup("hello");\n    printf("%s\\n", s);\n    s = strdup("world");\n    printf("%s\\n", s);\n}\n</code></pre>\n\n<p>You can see that the program works, but you have allocated memory (via malloc) without freeing it up.  You have lost your pointer to the first memory block when you called strdup the second time.</p>\n\n<p>This is no big deal for this small amount of memory, but consider the case:</p>\n\n<pre><code>for (i = 0; i &lt; 1000000000; ++i)  /* billion times */\n    s = strdup("hello world");    /* 11 bytes */\n</code></pre>\n\n<p>You have now used up 11 gig of memory (possibly more, depending on your memory manager) and if you have not crashed your process is probably running pretty slowly.</p>\n\n<p>To fix, you need to call free() for everything that is obtained with malloc() after you finish using it:</p>\n\n<pre><code>s = strdup("hello");\nfree(s);  /* now not leaking memory! */\ns = strdup("world");\n...\n</code></pre>\n\n<p>Hope this example helps!</p>\n'}, {'answer_id': 24912, 'author': 'Serge', 'author_id': 1007, 'author_profile': 'https://Stackoverflow.com/users/1007', 'pm_score': 2, 'selected': False, 'text': "<p>Also you might want to use dynamic memory allocation when you need to define a huge array, say int[10000]. You can't just put it in stack because then, hm... you'll get a stack overflow.</p>\n\n<p>Another good example would be an implementation of a data structure, say linked list or binary tree. I don't have a sample code to paste here but you can google it easily.</p>\n"}, {'answer_id': 24918, 'author': 'Chris B-C', 'author_id': 1517, 'author_profile': 'https://Stackoverflow.com/users/1517', 'pm_score': 3, 'selected': False, 'text': '<p>There are some great answers here about how to allocate and free memory, and in my opinion the more challenging side of using C is ensuring that the only memory you use is memory you\'ve allocated - if this isn\'t done correctly what you end up with is the cousin of this site - a buffer overflow - and you may be overwriting memory that\'s being used by another application, with very unpredictable results.</p>\n\n<p>An example:</p>\n\n<pre><code>int main() {\n    char* myString = (char*)malloc(5*sizeof(char));\n    myString = "abcd";\n}\n</code></pre>\n\n<p>At this point you\'ve allocated 5 bytes for myString and filled it with "abcd\\0" (strings end in a null - \\0).\nIf your string allocation was</p>\n\n<pre><code>myString = "abcde";\n</code></pre>\n\n<p>You would be assigning "abcde" in the 5 bytes you\'ve had allocated to your program, and the trailing null character would be put at the end of this - a part of memory that hasn\'t been allocated for your use and could be free, but could equally be being used by another application - This is the critical part of memory management, where a mistake will have unpredictable (and sometimes unrepeatable) consequences.</p>\n'}, {'answer_id': 24922, 'author': 'Euro Micelli', 'author_id': 2230, 'author_profile': 'https://Stackoverflow.com/users/2230', 'pm_score': 9, 'selected': True, 'text': "<p>There are two places where variables can be put in memory. When you create a variable like this:</p>\n<pre><code>int  a;\nchar c;\nchar d[16];\n</code></pre>\n<p>The variables are created in the &quot;<strong>stack</strong>&quot;. Stack variables are automatically freed when they go out of scope (that is, when the code can't reach them anymore). You might hear them called &quot;automatic&quot; variables, but that has fallen out of fashion.</p>\n<p>Many beginner examples will use only stack variables.</p>\n<p>The stack is nice because it's automatic, but it also has two drawbacks: (1) The compiler needs to know in advance how big the variables are, and (2) the stack space is somewhat limited. For example: in Windows, under default settings for the Microsoft linker, the stack is set to 1 MB, and not all of it is available for your variables.</p>\n<p>If you don't know at compile time how big your array is, or if you need a big array or struct, you need &quot;plan B&quot;.</p>\n<p>Plan B is called the &quot;<strong>heap</strong>&quot;. You can usually create variables as big as the Operating System will let you, but you have to do it yourself. Earlier postings showed you one way you can do it, although there are other ways:</p>\n<pre><code>int size;\n// ...\n// Set size to some value, based on information available at run-time. Then:\n// ...\nchar *p = (char *)malloc(size);\n</code></pre>\n<p>(Note that variables in the heap are not manipulated directly, but via pointers)</p>\n<p>Once you create a heap variable, the problem is that the compiler can't tell when you're done with it, so you lose the automatic releasing. That's where the &quot;manual releasing&quot; you were referring to comes in. Your code is now responsible to decide when the variable is not needed anymore, and release it so the memory can be taken for other purposes. For the case above, with:</p>\n<pre><code>free(p);\n</code></pre>\n<p>What makes this second option &quot;nasty business&quot; is that it's not always easy to know when the variable is not needed anymore. Forgetting to release a variable when you don't need it will cause your program to consume more memory that it needs to. This situation is called a &quot;leak&quot;. The &quot;leaked&quot; memory cannot be used for anything until your program ends and the OS recovers all of its resources. Even nastier problems are possible if you release a heap variable by mistake <em>before</em> you are actually done with it.</p>\n<p>In C and C++, you are responsible to clean up your heap variables like shown above. However, there are languages and environments such as Java and .NET languages like C# that use a different approach, where the heap gets cleaned up on its own. This second method, called &quot;garbage collection&quot;, is much easier on the developer but you pay a penalty in overhead and performance. It's a balance.</p>\n<p><em>(I have glossed over many details to give a simpler, but hopefully more leveled answer)</em></p>\n"}, {'answer_id': 25068, 'author': 'Anders Eurenius', 'author_id': 1421, 'author_profile': 'https://Stackoverflow.com/users/1421', 'pm_score': 2, 'selected': False, 'text': '<p>(I\'m writing because I feel the answers so far aren\'t quite on the mark.)</p>\n\n<p>The reason you have to memory management worth mentioning is when you have a problem / solution that requires you to create complex structures. (If your programs crash if you allocate to much space on the stack at once, that\'s a bug.) Typically, the first data structure you\'ll need to learn is some kind of <a href="http://en.wikipedia.org/wiki/Linked_List" rel="nofollow noreferrer">list</a>. Here\'s a single linked one, off the top of my head:</p>\n\n<pre><code>typedef struct listelem { struct listelem *next; void *data;} listelem;\n\nlistelem * create(void * data)\n{\n   listelem *p = calloc(1, sizeof(listelem));\n   if(p) p-&gt;data = data;\n   return p;\n}\n\nlistelem * delete(listelem * p)\n{\n   listelem next = p-&gt;next;\n   free(p);\n   return next;\n}\n\nvoid deleteall(listelem * p)\n{\n  while(p) p = delete(p);\n}\n\nvoid foreach(listelem * p, void (*fun)(void *data) )\n{\n  for( ; p != NULL; p = p-&gt;next) fun(p-&gt;data);\n}\n\nlistelem * merge(listelem *p, listelem *q)\n{\n  while(p != NULL &amp;&amp; p-&gt;next != NULL) p = p-&gt;next;\n  if(p) {\n    p-&gt;next = q;\n    return p;\n  } else\n    return q;\n}\n</code></pre>\n\n<p>Naturally, you\'d like a few other functions, but basically, this is what you need memory management for. I should point out that there are a number tricks that are possible with "manual" memory management, e.g.,</p>\n\n<ul>\n<li>Using the fact that <a href="http://en.wikipedia.org/wiki/Malloc" rel="nofollow noreferrer">malloc</a> is guaranteed (by the language standard) to return a pointer divisible by 4,</li>\n<li>allocating extra space for some sinister purpose of your own,</li>\n<li>creating <a href="http://en.wikipedia.org/wiki/Memory_pool" rel="nofollow noreferrer">memory pool</a>s..</li>\n</ul>\n\n<p><em>Get a good debugger...</em> Good luck!</p>\n'}, {'answer_id': 26326, 'author': 'Euro Micelli', 'author_id': 2230, 'author_profile': 'https://Stackoverflow.com/users/2230', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n<p>@<a href="https://stackoverflow.com/questions/24891/c-memory-management#25084">Ted Percival</a>:<br />\n...you don\'t need to cast malloc()\'s return value.</p>\n</blockquote>\n<p>You are correct, of course. I believe that has always been true, although I don\'t have a copy of <a href="http://en.wikipedia.org/wiki/The_C_Programming_Language_%28book%29" rel="nofollow noreferrer" title="&quot;The C Programming Language&quot;, by B. Kernighan and D. Ritchie">K&amp;R</a> to check.</p>\n<p>I don\'t like a lot of the implicit conversions in C, so I tend to use casts to make &quot;magic&quot; more visible. Sometimes it helps readability, sometimes it doesn\'t, and sometimes it causes a silent bug to be caught by the compiler. Still, I don\'t have a strong opinion about this, one way or another.</p>\n<blockquote>\n<p>This is especially likely if your compiler understands C++-style comments.</p>\n</blockquote>\n<p>Yeah... you caught me there. I spend a lot more time in C++ than C. Thanks for noticing that.</p>\n'}, {'answer_id': 26378, 'author': 'Jonathan Branam', 'author_id': 2347, 'author_profile': 'https://Stackoverflow.com/users/2347', 'pm_score': 0, 'selected': False, 'text': '<p>@<a href="https://stackoverflow.com/questions/24891/c-memory-management#24922">Euro Micelli</a></p>\n\n<p>One negative to add is that pointers to the stack are no longer valid when the function returns, so you cannot return a pointer to a stack variable from a function. This is a common error and a major reason why you can\'t get by with just stack variables. If your function needs to return a pointer, then you have to malloc and deal with memory management.</p>\n'}, {'answer_id': 29952, 'author': 'magice', 'author_id': 227049, 'author_profile': 'https://Stackoverflow.com/users/227049', 'pm_score': 0, 'selected': False, 'text': '<p>In C, you actually have two different choices. One, you can let the system manage the memory for you. Alternatively, you can do that by yourself. Generally, you would want to stick to the former as long as possible. However, auto-managed memory in C is extremely limited and you will need to manually manage the memory in many cases, such as:</p>\n\n<p>a. You want the variable to outlive the functions, and you don\'t want to have global variable. ex:</p>\n\n<pre>\nstruct pair{\n   int val;\n   struct pair *next;\n}\n\nstruct pair* new_pair(int val){\n   struct pair* np = malloc(sizeof(struct pair));\n   np->val = val;\n   np->next = NULL;\n   return np;\n}\n</pre>\n\n<p>b. you want to have dynamically allocated memory. Most common example is array without fixed length:</p>\n\n<pre>\nint *my_special_array;\nmy_special_array = malloc(sizeof(int) * number_of_element);\nfor(i=0; i\n\n<p>c. You want to do something REALLY dirty. For example, I would want a struct to represent many kind of data and I don\'t like union (union looks soooo messy):</p>\n\n\nstruct data{\n  int data_type;\n  long data_in_mem;\n};\n\nstruct animal{/*something*/};\nstruct person{/*some other thing*/};\n\nstruct animal* read_animal();\nstruct person* read_person();\n\n/*In main*/\nstruct data sample;\nsampe.data_type = input_type;\nswitch(input_type){\n case DATA_PERSON:\n   sample.data_in_mem = read_person();\n   break;\n case DATA_ANIMAL:\n   sample.data_in_mem = read_animal();\n default:\n   printf("Oh hoh! I warn you, that again and I will seg fault your OS");\n}\n</pre>\n\n<p>See, a long value is enough to hold ANYTHING. Just remember to free it, or you WILL regret. This is among my favorite tricks to have fun in C :D.</p>\n\n<p>However, generally, you would want to stay away from your favorite tricks (T___T). You WILL break your OS, sooner or later, if you use them too often. As long as you don\'t use *alloc and free, it is safe to say that you are still virgin, and that the code still looks nice.</p>\n'}, {'answer_id': 38776, 'author': 'Bill Forster', 'author_id': 3955, 'author_profile': 'https://Stackoverflow.com/users/3955', 'pm_score': 3, 'selected': False, 'text': "<p>I think the most concise way to answer the question in to consider the role of the pointer in C. The pointer is a lightweight yet powerful mechanism that gives you immense freedom at the cost of immense capacity to shoot yourself in the foot.</p>\n\n<p>In C the responsibility of ensuring your pointers point to memory you own is yours and yours alone. This requires an organized and disciplined approach, unless you forsake pointers, which makes it hard to write effective C.</p>\n\n<p>The posted answers to date concentrate on automatic (stack) and heap variable allocations. Using stack allocation does make for automatically managed and convenient memory, but in some circumstances (large buffers, recursive algorithms) it can lead to the horrendous problem of stack overflow. Knowing exactly how much memory you can allocate on the stack is very dependent on the system. In some embedded scenarios a few dozen bytes might be your limit, in some desktop scenarios you can safely use megabytes.</p>\n\n<p>Heap allocation is less inherent to the language. It is basically a set of library calls that grants you ownership of a block of memory of given size until you are ready to return ('free') it. It sounds simple, but is associated with untold programmer grief. The problems are simple (freeing the same memory twice, or not at all [memory leaks], not allocating enough memory [buffer overflow], etc)  but difficult to avoid and debug. A hightly disciplined approach is absolutely mandatory in practive but of course the language doesn't actually mandate it.</p>\n\n<p>I'd like to mention another type of memory allocation that's been ignored by other posts. It's possible to statically allocate variables by declaring them outside any function. I think in general this type of allocation gets a bad rap because it's used by global variables. However there's nothing that says the only way to use memory allocated this way is as an undisciplined global variable in a mess of spaghetti code. The static allocation method can be used simply to avoid some of the pitfalls of the heap and automatic allocation methods. Some C programmers are surprised to learn that large and sophisticated C embedded and games programs have been constructed with no use of heap allocation at all.</p>\n"}, {'answer_id': 695566, 'author': 'Hernán', 'author_id': 48026, 'author_profile': 'https://Stackoverflow.com/users/48026', 'pm_score': 2, 'selected': False, 'text': '<p>A thing to remember is to <em>always</em> initialize your pointers to NULL, since an uninitialized pointer may contain a pseudorandom valid memory address which can make pointer errors go ahead silently. By enforcing a pointer to be initialized with NULL, you can always catch if you are using this pointer without initializing it. The reason is that operating systems "wire" the virtual address 0x00000000 to general protection exceptions to trap null pointer usage.</p>\n'}]
['https://Stackoverflow.com/questions/24891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2128/']