Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Break down your statement</p> <pre><code>char* name = malloc(256*sizeof(char)); // one statement char *name; // Step 1 declare pointer to character name = malloc(256*sizeof(char)); // assign address to pointer of memory from heap name[2]; // access 3rd item in array *(name+2); // access 3rd item in array name++; // move name to item 1 </code></pre> <p>Translation: name is now a pointer to character which is assigned the address of some memory on the heap</p> <pre><code>char name[256]; // declare an array on the stack name++; // error name is a constant pointer *(name+2); // access 3rd item in array name[2]; // access 3rd item in array char *p = name; p[2]; // access 3rd item in array *(p+2); // access 3rd item in array p++; // move p to item 1 p[0]; // item 1 in array </code></pre> <p>Translation: Name is a constant pointer to a character that points to some memory on the stack</p> <p>In C arrays and pointers are the same thing more or less. Arrays are constant pointers to memory. The main difference is that when you call malloc you take your memory from the heap and any memory taken from the heap must be freed from the heap. When you declare the array with a size it is assigned memory from the stack. You can't free this memory because free is made to free memory from the heap. The memory on the stack will automatically be freed when the current program unit returns. In the second example free(p) would be an error also. p is a pointer the name array on the stack. So by freeing p you are attempting to free the memory on the stack.</p> <p>This is no different from:</p> <pre><code>int n = 10; int *p = &amp;n; </code></pre> <p>freeing p in this case would be an error because p points to n which is a variable on the stack. Therefore p holds a memory location in the stack and cannot be freed.</p> <pre><code>int *p = (int *) malloc(sizeof(int)); *p = 10; free(p); </code></pre> <p>in this case the free is correct because p points to a memory location on the heap which was allocated by malloc.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload