<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
  xmlns:content="http://purl.org/rss/1.0/modules/content/"
  xmlns:wfw="http://wellformedweb.org/CommentAPI/"
  xmlns:dc="http://purl.org/dc/elements/1.1/"
  xmlns:atom="http://www.w3.org/2005/Atom"
  xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
  xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
  >

<channel>
<title>Vert Studios - Programming Blog</title>
<atom:link href="http://www.vertstudios.com/blog/feed/" rel="self" type="application/rss+xml"/>
<link>http://www.vertstudios.com/blog</link>
<description>Programming tutorials and screencasts geared towards the 
beginner-intermediate programmer.</description>
<lastBuildDate>Sat, 15 Sep 2018 18:47:34 +0000</lastBuildDate>
<language>en</language>


<item>
  <title>[Screencast] C: malloc and functions returning pointers</title>
  <link>http://vertstudios.com/blog/malloc-functions-returning-pointers</link>
  <pubDate>Wed, 25 Jul 2012 07:45:00 +0000</pubDate>
  <description>Explanation and examples of using the malloc function. Also, how
to create/use functions that return pointers.</description>
  <content:encoded>&lt;h1&gt;&lt;a href="/blog/malloc-functions-returning-pointers"&gt;[Screencast] C: malloc and functions returning pointers&lt;/a&gt;&lt;/h1&gt;
    
&lt;iframe width="600" height="365" src="http://www.youtube.com/embed/3JX6TyLOmGQ" frameborder="0" allowfullscreen=""/&gt;

&lt;p&gt;&lt;br/&gt;&lt;/p&gt;
&lt;p&gt;(&lt;strong&gt;The video above is optional&lt;/strong&gt;, and covers no more material than what is
covered here. If you like to read and work through things at your own pace, the
full article text is below. If you prefer to observe and listen, feel free to
enjoy the screencast.)&lt;/p&gt;
&lt;p&gt;Before you proceed with this tutorial, you should have a good understanding of
pointers. Check out my &lt;a href="/blog/introduction-pointers-in-c/"&gt;introduction to pointers&lt;/a&gt; screencast.&lt;/p&gt;
&lt;p&gt;The ability to manage your own memory is part of what makes C so significant.
At the heart of memory management sits &lt;code&gt;malloc&lt;/code&gt;, a function which you will know
how to use by the end of this tutorial.&lt;/p&gt;
&lt;p&gt;As described by the &lt;a href="http://www.gnu.org/software/libc/manual/html_node/Basic-Allocation.html"&gt;GNU&lt;/a&gt;, the &lt;code&gt;malloc&lt;/code&gt; function is used to manually
allocate a block of memory. Specifically, &lt;code&gt;malloc&lt;/code&gt; returns a pointer to a newly
allocated block of memory. This brings up the question: &lt;strong&gt;What does it mean to
return a pointer?&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;Functions returning Pointers&lt;/h2&gt;
&lt;p&gt;Similar to how a C function can return an &lt;code&gt;int&lt;/code&gt; or &lt;code&gt;char&lt;/code&gt;, functions can also
return pointers. To demonstrate, let's use the most basic functions possible.
First, an &lt;code&gt;int&lt;/code&gt; function that just returns the integer passed to it.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Demonstrate a simple function that returns an integer.
#include&amp;lt;stdio.h&amp;gt;

int return_me(int);

int main(){
  int x = 5;
  printf("x: %d\n", x);

  x = return_me(x);
  printf("x: %d\n", x);

  return 0;
}

/*
 * A very simple function: Just returns the integer passed to it!
 */
int return_me(int num){
  return num;
}
&lt;/pre&gt;

&lt;p&gt;After compiling and running, the output is just&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
x: 5
x: 5
&lt;/pre&gt;

&lt;p&gt;Now let's take this same idea, but now we'll apply it to pointers.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Demonstrate a simple function that returns a pointer to int
#include&amp;lt;stdio.h&amp;gt;

int* return_me(int*);

int main(){
  int x = 5;

  // p holds the memory address of the integer x.
  int *p = &amp;amp;x;
  printf("p: %p\n", p);

  p = return_me(p);
  printf("p: %p\n", p);

  return 0;
}

/*
 * A very simple function: Just returns the pointer passed to it!
 */
int* return_me(int *pointer){
  return pointer;
}

&lt;/pre&gt;

&lt;p&gt;The output will be similar to&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
p: 0x7fff678697fc
p: 0x7fff678697fc 
&lt;/pre&gt;

&lt;p&gt;Note the function header &lt;code&gt;int* return_me(int*)&lt;/code&gt;. We know the structure of a
function is &lt;/p&gt;
&lt;pre class="prettyprint"&gt;
returnType functionName(arg1, arg2, ...){
  // Do stuff
  // Return something of type returnType (unless void!)
}
&lt;/pre&gt;

&lt;p&gt;So it makes sense that if we wanted to return the memory address of an integer,
also known as a "pointer to int", we would specify our return type as &lt;code&gt;int*&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;For another example, say we have two floating point variables &lt;code&gt;x&lt;/code&gt; and &lt;code&gt;y&lt;/code&gt;. We
want to create a function that returns the address of the larger variable. Here
is how we would accomplish this:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// This program contains a simple function that returns a pointer to float.
#include&amp;lt;stdio.h&amp;gt;

float* return_biggest(float*, float*);

int main(){
  float x = 10.0;
  float y = 20.0;

  // Get the address of the variable with the largest value.
  float *p = return_biggest(&amp;amp;x, &amp;amp;y);

  printf("(x) addr: %p, val: %.2f \n", &amp;amp;x, x);
  printf("(y) addr: %p, val: %.2f \n", &amp;amp;y, y);
  printf("The address of the biggest: %p\n", p);
  printf("The value of the biggest: %.2f\n", *p);
  return 0;
}

/*
 * Returns the address of the float variable with the largest value.
 */
float* return_biggest(float *p1, float *p2){
  // biggest is a pointer to float: it will hold the memory address of a
  // floating point variable.
  float *biggest;
  if (*p1 &amp;gt; *p2){
    // biggest is assigned the memory address of the float associated with 
    // the address p1
    biggest = p1;
  }
  else{
    // biggest is assigned the memory address of the float associated with 
    // the address p2
    biggest = p2;
  }

  // return the memory address of the larger float variable
  return biggest;
}

&lt;/pre&gt;

&lt;p&gt;The output will look similar to&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
(x) addr: 0x7fff57c94728, val: 10.00
(y) addr: 0x7fff57c9472c, val: 20.00
The address of the biggest: 0x7fff57c9472c
The value of the biggest: 20.00  
&lt;/pre&gt;

&lt;p&gt;Specifically, the address of &lt;code&gt;y&lt;/code&gt; and the address of the biggest should be
identical.&lt;/p&gt;
&lt;h2&gt;Void pointers&lt;/h2&gt;
&lt;p&gt;We know a pointer to int must hold the address of an int, a pointer to float
must hold the address of a float, and so on. However, there does a exist a
special pointer type that can be assigned the memory address of any type: These
pointers are called &lt;strong&gt;void pointers&lt;/strong&gt;. We declare and assign void pointers just
like any other pointer. Observe in the following example how the void pointer
can be assigned the address of both a float and an int:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Void pointers
#include&amp;lt;stdio.h&amp;gt;

int main(){
  int x = 10;
  float y = 20.0;

  void *p = &amp;amp;x;
  printf("p: %p\n", p);

  p = &amp;amp;y;
  printf("p: %p\n", p);
  return 0;
}
&lt;/pre&gt;

&lt;p&gt;With the output looking similar to&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
p: 0x7fffd3ea8dd8
p: 0x7fffd3ea8ddc
&lt;/pre&gt;

&lt;p&gt;Furthermore, void pointers are &lt;strong&gt;assignable&lt;/strong&gt; to any other pointer type. In
other words, a void pointer can be assigned to any pointer variable of any
type. To demonstrate:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Void pointers are assignable to any pointer type
#include&amp;lt;stdio.h&amp;gt;

int main(){
  // Initialize x and y
  int x = 10;
  float y = 20.0;

  // Declare a pointer to int, float, and a void pointer
  int *pint;
  float *pfloat;
  void *vp;

  // Assign vp the memory address of x, a pointer to int.
  vp = &amp;amp;x;
  pint = vp;

  // Assign vp the memory address of y, a pointer to float.
  pfloat = vp;

  return 0;
}


&lt;/pre&gt;

&lt;h3&gt;Functions returning void pointers.&lt;/h3&gt;
&lt;p&gt;If we can declare a variable of type &lt;code&gt;void*&lt;/code&gt;, then we certainly can create a
function returning a value of type &lt;code&gt;void*&lt;/code&gt;, which is simply a pointer of any
type.&lt;/p&gt;
&lt;p&gt;Consider a previous example which simply returns the pointer to int passed to
it. We can modify the function to return a void pointer, and the result will be
the same.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Demonstrate a simple function that returns a void pointer
#include&amp;lt;stdio.h&amp;gt;

void* return_me(int*);

int main(){
  int x = 5;

  // p holds the memory address of the integer x.
  int *p = &amp;amp;x;
  printf("p: %p\n", p);

  p = return_me(p);
  printf("p: %p\n", p);

  return 0;
}

/*
 * A very simple function: Just returns the pointer passed to it!
 */
void* return_me(int *pointer){
  return pointer;
}

&lt;/pre&gt;

&lt;p&gt;It's always better to be explicit when possible, though. Usually you will know
exactly what type of pointer you want returned, so for the sake of your sanity
(and the sanity of those around you), don't make all your functions returning
a pointer be of type &lt;code&gt;void*&lt;/code&gt; just to save yourself a few keystrokes.&lt;/p&gt;
&lt;p&gt;At this point, void pointers appear to function just like, let's say, a pointer
to int.  However, there are strict rules and pitfalls that come with void
pointers that do not with other pointers.&lt;/p&gt;
&lt;h3&gt;Dereferencing Void Pointers - It can't be done!&lt;/h3&gt;
&lt;p&gt;Although void pointers and other pointers have many things in common, the
ability to dereference is not one of them. This is because other pointer types
tell the compiler how much memory should be read/written when we deference
them, but void pointers do not us with this information.&lt;/p&gt;
&lt;p&gt;The following program will fail to compile:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Attempt to dereference a void pointer: This will fail to compile!
#include&amp;lt;stdio.h&amp;gt;

int main(){
  // Get the address of an integer
  int x = 10;
  void* vp = &amp;amp;x;
  *vp = 15;

  printf("The value at the address of vp is: %d\n", *vp);
  return 0;
}

&lt;/pre&gt;

&lt;p&gt;My gcc compiler outputs&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
ex8.c: In function &amp;#8216;main&amp;#8217;:
ex8.c:10: warning: dereferencing &amp;#8216;void *&amp;#8217; pointer
ex8.c:10: error: invalid use of void expression
ex8.c:12: warning: dereferencing &amp;#8216;void *&amp;#8217; pointer
ex8.c:12: error: invalid use of void expression
&lt;/pre&gt;

&lt;p&gt;We can, however, cast a void pointer to the proper pointer type, and then
dereference. &lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Attempt to dereference a void pointer: Casting works!
#include&amp;lt;stdio.h&amp;gt;

int main(){
  // Get the address of an integer
  int x = 10;
  void* vp = &amp;amp;x;

  printf("The value at the address of vp is: %d\n", *(int*)vp);
  return 0;
}
&lt;/pre&gt;

&lt;p&gt;With the expected output of&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
The value at the address of vp is: 10
&lt;/pre&gt;

&lt;h3&gt;Implicit conversion of void pointers&lt;/h3&gt;
&lt;p&gt;Luckily, even though we can't dereference a void pointer, we don't have to cast
a void pointer if it's being assigned to another pointer. Look at the
following example, and reread the previous sentence a few times until it sinks
in.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Demonstrate implicit conversion of void pointers
#include&amp;lt;stdio.h&amp;gt;

int main(){
  // Initialize an integer x
  int x = 10;

  // Assign the address of x to a void pointer
  void *vp = &amp;amp;x;

  // Initialize a pointer to int to vp, which itself is the address of x.
  int *pint = vp;

  // We're free to dereference pint: Even though vp is a void pointer, the
  // assignment above initiated an implicit conversion of vp to a pointer to
  // int, similar to how `float x = 10` implicitly converts 10 to its floating
  // point form. Dereferencing vp at this point would still result in an error:
  // it's never okay to dereference a void pointer.
  printf("*pint: %d\n", *pint);

  return 0;
}
&lt;/pre&gt;

&lt;p&gt;The output: &lt;/p&gt;
&lt;pre class="prettyprint"&gt;
*pint: 10
&lt;/pre&gt;

&lt;p&gt;We take advantage of the implicit conversion behavior of assigning void
pointers to "normal" pointers every time we use &lt;code&gt;malloc&lt;/code&gt;, which you'll see in a
few minutes.&lt;/p&gt;
&lt;h3&gt;Playing with Fire&lt;/h3&gt;
&lt;p&gt;We knew beforehand we can't assign the address of a float to a pointer to int.
But now, we know void pointers are implicitly converted to the type of pointer
it's being assigned to. If we're feeling smug, we might think:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;What if I assign a void pointer holding a pointer to float to a pointer to
int? &lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Indeed, this trickery will compile!&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Void pointers are assignable to any pointers
#include&amp;lt;stdio.h&amp;gt;

int main(){
    // Initialize an integer
  int x = 10;

  // Declare pointers to int and float
  int *pint;
  float *pfloat;

  // Initialize a void pointer to the memory address of the integer x
  void* vp = &amp;amp;x;

  // Since void pointers are assignable to any pointer, the following are both
  // legal (but legal doesn't always mean smart or safe!).
  pint = vp;
  pfloat = vp;

  // This makes sense because pint is a pointer to int, and vp holds the
  // memory address of an integer.
  printf("*pint: %d\n", *pint);

  // But this doesn't make sense because pfloat is a pointer to float, but
  // vp holds the memory address of an integer.
  *pfloat = 10.0;
  printf("*pfloat: %f\n", *pfloat);

  // Now our data has been corrupted. Lesson learned: Just because void
  // pointers are legally assignable to everything doesn't mean you're safe!
  printf("*pint: %d\n", *pint);

  return 0;
}


&lt;/pre&gt;

&lt;p&gt;Output will appear similar to 
&lt;/p&gt;&lt;pre class="prettyprint"&gt;
&lt;em&gt;pint: 10
&lt;/em&gt;pfloat: 10.000000
*pint: 1092616192
&lt;/pre&gt;
&lt;p&gt;This behavior is explained in this &lt;a href="http://stackoverflow.com/a/99010/670823"&gt;StackOverflow thread&lt;/a&gt;,&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;... dereferencing a pointer that aliases another of an incompatible type is
undefined behavior. Unfortunately you can still code this way, maybe* get some
warnings, have it compile fine, only to have weird unexpected behavior when you
run the code.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;One thing that you will learn about C, if you haven't already, is that legal
does not necessarily imply correct, and correct now does not necessarily imply
correct forever! Be careful.&lt;/p&gt;
&lt;h2&gt;Allocating Memory with malloc&lt;/h2&gt;
&lt;p&gt;If you look closely at the previous examples when functions returned pointers,
we've only returned pointers that were declared in &lt;code&gt;main()&lt;/code&gt; and passed to the
function. What if I wanted a function to return the address of a variable
declared inside the function?&lt;/p&gt;
&lt;h3&gt;What not to do&lt;/h3&gt;
&lt;p&gt;We know that initialization statements like &lt;code&gt;int x = 10&lt;/code&gt; allocate memory, and
that allocated memory has an address. Consequently, the following example
appears to be a sufficient way to allot memory for a variable and return its
address.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Example of how NOT to allocate memory!!!
#include&amp;lt;stdio.h&amp;gt;

int* new_integer(void);

int main(){
  // Get the address of an integer
  int *p;
  p = new_integer();

  printf("The value at the address of p is: %d\n", *p);
  return 0;
}

int* new_integer(void){
  int x = 10;
  return &amp;amp;x;
}
&lt;/pre&gt;

&lt;p&gt;Returning the address of a local variable, however, is &lt;strong&gt;undefined behavior&lt;/strong&gt;.
It might work as "expected" for a short period of time and fail later. Why is
that? This comment from &lt;a href="http://www.reddit.com/r/programming/comments/vuf6l/worst_c_tutorial_ever/c57sizf"&gt;/r/programming&lt;/a&gt; explains the issue very well:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Once the function [a local variable] is defined in returns, the memory used
for storing that variable will be "freed" and almost certainly reused at some
point in the future. Returning a pointer to a [local] variable ...  means that
you are returning a pointer to memory that can be overwritten at any time.
Reading or writing to that variable can cause any number of bad things to
happen, including data corruption and crashes. Worse, it may work fine, at
least for a while, making it very difficult to debug.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;It is mandatory that you understand &lt;a href="http://www.maxi-pedia.com/what+is+heap+and+stack"&gt;the heap and the stack&lt;/a&gt;, but for this
tutorial, the explanation above will suffice.&lt;/p&gt;
&lt;h3&gt;What to do - malloc!&lt;/h3&gt;
&lt;p&gt;Now that we understand how &lt;em&gt;not&lt;/em&gt; to allocate memory, we can discuss how you
should allocate memory. For this tutorial, we will use the &lt;code&gt;malloc&lt;/code&gt; function
for allocating memory, although &lt;a href="http://www.gnu.org/software/libc/manual/html_node/Unconstrained-Allocation.html"&gt;other allocation functions exist&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The definition of &lt;code&gt;malloc&lt;/code&gt; is as follows:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;
void* malloc (size_t size)&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;This function returns a pointer to a newly allocated block size bytes long,
or a null pointer if the block could not be allocated.&lt;br/&gt;
&lt;/p&gt;
&lt;p&gt;For all intents and purposes, you can consider &lt;code&gt;size_t&lt;/code&gt; (read "size type") as
an unsigned integer. (More discussion on &lt;a href="http://stackoverflow.com/questions/994288/size-t-vs-int-in-c-and-or-c"&gt;size_t vs int&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;So when calling the &lt;code&gt;malloc&lt;/code&gt; function, you specify how many bytes of memory you
want allocated, and if malloc is able to allocate that memory, it returns a
void pointer to that memory block. &lt;/p&gt;
&lt;p&gt;Let's take our incorrect example and fix it by implementing &lt;code&gt;malloc&lt;/code&gt;.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Allocating memory with malloc
#include&amp;lt;stdio.h&amp;gt;
#include&amp;lt;stdlib.h&amp;gt; // required to use malloc

int* new_integer(void);

int main(){
  // Get the address of an integer
  int *p;
  p = new_integer();
  *p = 15;

  printf("The value at the address of p is: %d\n", *p);
  return 0;
}

int* new_integer(void){
  // Allocate the exact amount of memory needed for an integer via sizeof(int).
  // malloc returns a void pointer, but the assignment to `int *pointer` causes
  // an implicit conversion to type int*.
  int *pointer = malloc(sizeof(int));
  return pointer;
}
&lt;/pre&gt;

&lt;p&gt;Be sure to note the inclusion of the &lt;code&gt;stdlib.h&lt;/code&gt; library, as well as the usage
of the &lt;code&gt;sizeof&lt;/code&gt; operator. &lt;code&gt;sizeof&lt;/code&gt; tells us the number of bytes a datatype or
variable takes up in memory. &lt;/p&gt;
&lt;p&gt;While this example demonstrates how to use &lt;code&gt;malloc&lt;/code&gt;, it's not particularly
useful in any real world scenario. &lt;code&gt;malloc&lt;/code&gt; really begins to shine when we
start creating data structures such as linked lists, stacks, queues, binary
trees, and more. The process of creating linked lists, which will be the
subject of my next article, frequently involves allocating memory for a
&lt;a href="/blog/structures-in-c/"&gt;structure&lt;/a&gt;. Here's an example of dynamically allocating memory for a
structure using malloc:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Using malloc to allocate memory for a structure
#include&amp;lt;stdio.h&amp;gt;
#include&amp;lt;stdlib.h&amp;gt;

// Create a 'rectangle' structure.
typedef struct{
  int height;
  int width;
} rec_t;

rec_t* new_rectangle(void);

int main(){
  // Declare a pointer to a rectangle structure. `ptr` will hold the memory
  // address of a structure.
  rec_t *ptr;
  ptr = new_rectangle();

  // Now that ptr has the memory address of a rectangle structure, we can
  // perform operations on *ptr just like we would any other structure.
  // In this case, assignment to another structure variable.
  rec_t rectangle = *ptr;

  rectangle.width = 10;
  rectangle.height = 10;

  // Display the dimensions.
  printf("The height: %d\nThe width: %d\n", rectangle.width, rectangle.height);

  return 0;
}

rec_t* new_rectangle(void){
  // Allocate the exact right amount of memory for a rectangle structure.
  // Due to how the sizeof operator works, we can use a "shortcut" and get
  // the number of bytes needed without having to specify the rec_t type to
  // sizeof. 
  rec_t *p = malloc(sizeof *p);
  return p;
}
&lt;/pre&gt;

&lt;p&gt;Take a good look at the &lt;code&gt;new_rectangle&lt;/code&gt; function, and take a couple minutes to
just memorize that initialization of p. It is not necessary to specify &lt;code&gt;rec_t&lt;/code&gt;,
because the compiler knows that &lt;code&gt;*p&lt;/code&gt; is of that type. It might seem strange that
we can refer to &lt;code&gt;*p&lt;/code&gt; in the initialization of &lt;code&gt;p&lt;/code&gt;, but we can! This type of
call to malloc is much more concise and accurate.&lt;/p&gt;
&lt;p&gt;In the proceeding example, where we used &lt;code&gt;malloc(sizeof(int))&lt;/code&gt;, we could have
used &lt;code&gt;malloc(sizeof *pointer)&lt;/code&gt; instead.&lt;/p&gt;
&lt;p&gt;In many tutorials/discussion forums, you probably would have seen the
&lt;code&gt;new_rectangle&lt;/code&gt; function in the following form:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
rec_t* new_rectangle(void){
  rec_t *p = (rec_t*)malloc(sizeof(rec_t));
  return p;
}
&lt;/pre&gt;

&lt;p&gt;Earlier I claimed that "explicit is always better". The above, however, is 
overly-verbose to the &lt;a href="http://stackoverflow.com/a/605858/670823"&gt;point of being harmful&lt;/a&gt;. Keep it simple!&lt;/p&gt;
&lt;h2&gt;Freeing Allocated Memory&lt;/h2&gt;
&lt;p&gt;When you no longer need memory you've allocated with &lt;code&gt;malloc&lt;/code&gt;, you can pass
the address returned by &lt;code&gt;malloc&lt;/code&gt; to the &lt;code&gt;free&lt;/code&gt; function, and that memory will
be freed up.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Allocate memory, store the memory block address in rec
rec_t *rec = malloc(sizeof *rec);

// Do stuff with rec
// ...
// ...
// ...

// Free the memory block located at the memory address `rec`
free(rec);
&lt;/pre&gt;

&lt;h2&gt;What comes next?&lt;/h2&gt;
&lt;p&gt;With a basic understanding of functions that return pointers and how to use
&lt;code&gt;malloc&lt;/code&gt;, and a little more knowledge of the interactions between pointers and
structures, we'll be on our way to creating data structures!&lt;/p&gt;</content:encoded>
</item>

<item>
  <title>[Screencast] Beginner's Introduction to Pointers in C</title>
  <link>http://vertstudios.com/blog/introduction-pointers-in-c</link>
  <pubDate>Wed, 18 Jul 2012 11:03:00 +0000</pubDate>
  <description>An easy, accessible introduction to using pointers in C.</description>
  <content:encoded>&lt;h1&gt;&lt;a href="/blog/introduction-pointers-in-c"&gt;[Screencast] Beginner's Introduction to Pointers in C&lt;/a&gt;&lt;/h1&gt;
    
&lt;p&gt;&lt;strong&gt;Pointers aren't that hard&lt;/strong&gt;. You might find that hard to believe, but it's
true!  Unfortunately, the simplicity of pointers tends to get lost in poor or
overly-verbose explanations. This is my attempt to present pointers in a clear,
easy, and accessible manner.&lt;/p&gt;
&lt;p&gt;This screencast answers the following question:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;What is a pointer, and why are they important?&lt;/li&gt;
&lt;li&gt;How do I declare a pointer?&lt;/li&gt;
&lt;li&gt;What does it mean to 'dereference' a pointer?&lt;/li&gt;
&lt;li&gt;How do I handle pointers inside a function?&lt;/li&gt;
&lt;/ul&gt;
&lt;iframe width="600" height="365" src="http://www.youtube.com/embed/IkyWCOUY8V4" frameborder="0" allowfullscreen=""/&gt;

&lt;p&gt;&lt;br/&gt;&lt;/p&gt;</content:encoded>
</item>

<item>
  <title>Lock TwitchTV in Landscape Mode on your iPhone</title>
  <link>http://vertstudios.com/blog/twitchtv-landscape-lock</link>
  <pubDate>Sun, 15 Jul 2012 03:27:00 +0000</pubDate>
  <description>Step by step guide on how to lock your iPhone in Landscope mode
when watching TwitchTV.</description>
  <content:encoded>&lt;h1&gt;&lt;a href="/blog/twitchtv-landscape-lock"&gt;Lock TwitchTV in Landscape Mode on your iPhone&lt;/a&gt;&lt;/h1&gt;
    
&lt;p&gt;One of the most annoying aspects of iOS is the lack of a straightforward way to
lock your iPhone in Landscape mode. Portrait mode lock works just fine, but if
you're like me and enjoy watching &lt;a href="http://twitch.tv"&gt;TwitchTV&lt;/a&gt; in bed, Portrait
mode isn't that great for watching your favorite streams. If you attempt to
watch streams &lt;em&gt;without&lt;/em&gt; a lock of some form, though, you'll find your screen
constantly switching orientations.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;However&lt;/strong&gt;, landscape lock does exist, it just takes a bit of work to
activate!&lt;/p&gt;
&lt;h2&gt;Step by Step Guide&lt;/h2&gt;
&lt;p&gt;Open the Settings application. Scroll down and Press &lt;code&gt;General&lt;/code&gt;. Next, scroll
down and press &lt;code&gt;Accessibility&lt;/code&gt;. &lt;/p&gt;
&lt;p&gt;&lt;img src="/blog/images/twitchtv-landscape-lock/image1.png" alt="" class=""/&gt;&lt;/p&gt;
&lt;p&gt;Scroll down again until you see the &lt;code&gt;AssitiveTouch&lt;/code&gt; and &lt;code&gt;Triple-click Home&lt;/code&gt;
options. Set &lt;code&gt;AssitiveTouch&lt;/code&gt; to &lt;strong&gt;ON&lt;/strong&gt;  and &lt;code&gt;Triple-click Home&lt;/code&gt; to
&lt;strong&gt;AssitiveTouch&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src="/blog/images/twitchtv-landscape-lock/image2.png" alt="" class=""/&gt;&lt;/p&gt;
&lt;p&gt;The AssitiveTouch icon should pop up on your screen. If you don't see it,
press the Home button on the bottom of your iPhone three times in quick
succession.  After about five seconds, the icon should appear. Pressing the
Home button three times like this toggles the AssitiveTouch icon.&lt;/p&gt;
&lt;p&gt;&lt;img src="/blog/images/twitchtv-landscape-lock/image3.png" alt="" class=""/&gt;&lt;/p&gt;
&lt;p&gt;Next, &lt;a href="http://timeread.hubpages.com/hub/How-to-lock-the-iPod-touch-or-iPhone-screen-in-portrait-orientation"&gt;lock your iPhone orientation&lt;/a&gt; in Portrait mode.&lt;/p&gt;
&lt;p&gt;Now open up the TwitchTV app, and pull up your favorite stream. Press the
AssitiveTouch icon. A menu will pop up with the labels "Gestures", "Favorites",
"Device", and "Home". &lt;strong&gt;Press Device&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src="/blog/images/twitchtv-landscape-lock/image4.png" alt="" class=""/&gt;&lt;/p&gt;
&lt;p&gt;Another menu will come up. Choose &lt;strong&gt;Rotate Screen&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src="/blog/images/twitchtv-landscape-lock/image5.png" alt="" class=""/&gt;&lt;/p&gt;
&lt;p&gt;Finally, choose either &lt;strong&gt;Right&lt;/strong&gt; or &lt;strong&gt;Left&lt;/strong&gt; (Left to have the iPhone volume
buttons on top).&lt;/p&gt;
&lt;p&gt;&lt;img src="/blog/images/twitchtv-landscape-lock/image6.png" alt="" class=""/&gt;&lt;/p&gt;
&lt;p&gt;Now TwitchTV is locked in Landscape mode! Press anywhere outside of the
AssitiveTouch menu to minimize it, and feel free to toggle AssitiveTouch off
until you need it again.&lt;/p&gt;
&lt;h2&gt;A few things to remember&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;You will need to repeat this procedure any time you leave the TwitchTV App.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;You are able to drag the AssitiveTouch icon around on the screen. &lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;For whatever reason, toggling AssitiveTouch can take a really long time. If
AssitiveTouch fails to show up after triple-pressing the Home key, wait 10
seconds before trying again.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;</content:encoded>
</item>

<item>
  <title>How to Read a Programming Tutorial</title>
  <link>http://vertstudios.com/blog/how-to-read-programming-tutorial</link>
  <pubDate>Fri, 13 Jul 2012 01:16:00 +0000</pubDate>
  <description>Recommended steps to get the most out of a programming tutorial.</description>
  <content:encoded>&lt;h1&gt;&lt;a href="/blog/how-to-read-programming-tutorial"&gt;How to Read a Programming Tutorial&lt;/a&gt;&lt;/h1&gt;
    
&lt;p&gt;Many of us seek to improve ourselves beyond what's required. Many CS students
are not content to just make good grades in class; they want to get their hands
dirty with real-world projects. Many employees read up on the latest languages
and frameworks well beyond office hours, simply because they want to play with
technology while learning to build a better product. It's important, however, 
to ensure our time spent studying new programming techniques does not go to 
waste.&lt;/p&gt;
&lt;h2&gt;!(confused) != knowledgeable&lt;/h2&gt;
&lt;p&gt;Understanding an article does not necessarily grant you the knowledge to apply
it directly to your projects. I feel it's easy to mistake lack of confusion for
thorough understanding. In other words, you can glaze over an article and not
feel particularly puzzled by what you just read, yet still have no idea how to
reproduce any examples the moment you close the browser window. I use the following
techniques to help me determine if I've truly understood what I've read.&lt;/p&gt;
&lt;h3&gt;Ask Questions. Test Yourself!&lt;/h3&gt;
&lt;p&gt;if you come across something that doesn't sit right in your head, don't just
think "Hmm, okay, I guess that makes sense." Try to figure out &lt;em&gt;why&lt;/em&gt;, things
work, even if that involves moving beyond the article and searching through
Google.  Attempt to make slight adjustments to provided examples.  Change the
problem requirements if you're reading a book with provided exercises. The goal
is deep, applicable understanding of the subject, and changing examples and
problems will expose you to more edge cases, exceptions, and greatly accelerate
your understanding. Here are some examples:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;A C tutorial teaches you how to sort an array with hard-coded elements.
Can you alter the example to read inputs from the keyboard? How would you 
account for fewer/more inputs than the array size when sorting?&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;A git tutorial teaches you how to revert a commit. How could you revert
multiple commits at the same time if needed?&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;A rails tutorial has you storing user passwords using a SHA variant. Can
you alter the tutorial to implement bcrypt?&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Complete the examples, and then attempt to differentiate minor details from
the core concepts. Research the core concepts, and then apply the concepts by
changing up the minor details.&lt;/p&gt;
&lt;h3&gt;Could you recreate what you just read?&lt;/h3&gt;
&lt;p&gt;I touched on this earlier, but I firmly believe one should have the ability to
recreate examples from tutorials from memory. I would even go so far to claim
entire projects/applications, such as the Twitter clone from Hartl's free &lt;a href="http://ruby.railstutorial.org/ruby-on-rails-tutorial-book"&gt;Rails
book&lt;/a&gt;, should be
recreated from memory. Understanding code after glancing through it does &lt;strong&gt;not&lt;/strong&gt;
in any way guarantee you can replicate it, no matter how "trivial" you think it
is. Replicating code from memory forces you to think of the problem
requirements, the caveats, and it effectively exposes the concepts you didn't
even know you were unsure of.&lt;/p&gt;
&lt;h2&gt;Be Thorough, Be Honest&lt;/h2&gt;
&lt;p&gt;Reading programming tutorials effectively can be summarized in two words: 
thoroughness and honesty. Ask questions, alter examples, and never let your ego
pressure you to avoid topics you don't understand.&lt;/p&gt;</content:encoded>
</item>

<item>
  <title>Resize a Visual selection block to 80 width in VIM</title>
  <link>http://vertstudios.com/blog/resize-visual-block-vim</link>
  <pubDate>Fri, 13 Jul 2012 12:11:00 +0000</pubDate>
  <description>How to resize a visual block of text in VIM to have all lines of
that block be 80 width.</description>
  <content:encoded>&lt;h1&gt;&lt;a href="/blog/resize-visual-block-vim"&gt;Resize a Visual selection block to 80 width in VIM&lt;/a&gt;&lt;/h1&gt;
    
&lt;p&gt;Quick VIM tip today: Resizing a Visual selection block.&lt;/p&gt;
&lt;p&gt;Suppose you have a paragraph of text in a markdown document. You want this
paragraph to be composed of lines with a maximum width of 80. &lt;/p&gt;
&lt;p&gt;First, set your &lt;code&gt;textwidth&lt;/code&gt; to 80 via &lt;code&gt;:set tw=80&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Now you can quickly resize the paragraph by selecting it in Visual mode and
executing &lt;code&gt;gq&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Watch the demo below!&lt;/p&gt;
&lt;iframe width="560" height="315" src="http://www.youtube.com/embed/oc8XDHJY_FQ" frameborder="0" allowfullscreen=""/&gt;

&lt;p&gt;&lt;br/&gt;&lt;/p&gt;</content:encoded>
</item>

<item>
  <title>Structures in C Tutorial: The Basics</title>
  <link>http://vertstudios.com/blog/structures-in-c</link>
  <pubDate>Tue, 10 Jul 2012 11:36:00 +0000</pubDate>
  <description>A brief introduction to using Structures in C. Covers 
assignments, passing to function parameters, and structure declaration.</description>
  <content:encoded>&lt;h1&gt;&lt;a href="/blog/structures-in-c"&gt;Structures in C Tutorial: The Basics&lt;/a&gt;&lt;/h1&gt;
    
&lt;p&gt;This post serves as an introduction to using Structures in C! This is the first
of many C tutorials I plan on writing.&lt;/p&gt;
&lt;h2&gt;Reading this Tutorial&lt;/h2&gt;
&lt;p&gt;This tutorial is not meant to be quickly glossed over, unless of course you are
already familiar with the subject matter. Each full program (i.e. any snippets
beginning with &lt;code&gt;#include&lt;/code&gt;) should be hand-typed, compiled, and ran. I also 
encourage you to try to type the example programs entirely from memory once you
understand them; doing so helps me store new-found knowledge into long-term
memory, and perhaps you'll receive the same benefits!&lt;/p&gt;
&lt;h2&gt;What is a Structure?&lt;/h2&gt;
&lt;p&gt;As said by Neol Kalicharan in &lt;a href="http://www.amazon.com/Data-Structures-In-Noel-Kalicharan/dp/1438253273/"&gt;Data Structures in C&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;"In C, a structure is a collection of one or more variables, possibly of
different types, grouped together under a single name for convenient handling."&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Structures are pretty simple to understand just by seeing an example in action.
Compile and run the following:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Using structures in C
#include&amp;lt;stdio.h&amp;gt;

// Struct declaration
struct person{
  char *name;
  int age;
  char gender;
};

void print_person(struct person);

int main(){

  // Declaring a variable of type `struct person`
  struct person someguy;
  someguy.name = "Joseph";
  someguy.age = 21;
  someguy.gender = 'M';

  // Print person information
  print_person(someguy);

  return 0;
}

// Print a person's information
void print_person(struct person p){
  printf("Name: %s\n", p.name);
  printf("Age: %d\n", p.age);
  printf("Gender: %c\n", p.gender);
}
&lt;/pre&gt;

&lt;h3&gt;Explanation&lt;/h3&gt;
&lt;p&gt;In the Struct declaration section, we define a person type as a structure.
We then define the &lt;strong&gt;fields&lt;/strong&gt; of the structure: &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a pointer to char (to hold a string literal)&lt;/li&gt;
&lt;li&gt;age as an integer &lt;/li&gt;
&lt;li&gt;gender as a char.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Fields of the structure are accessed via the dot operator.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
#include&lt;stdio.h&gt;

struct product{
  char *label;
  int value;
};

int main(){

  struct product cookie;
  cookie.label = "wonderful cookie";
  cookie.value = 1;

  printf("The %s is $%d\n", cookie.label, cookie.value);

  return 0;
}
&lt;/stdio.h&gt;&lt;/pre&gt;

&lt;p&gt;After declaring the person structure, we can now do the same things with 
&lt;code&gt;struct person&lt;/code&gt; as we would regular data types, such as &lt;code&gt;int&lt;/code&gt;. &lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Declaring a variable
struct person someguy;
int x;

// Usage in function parameters
void print_person(struct person p){
  ... // Do things with p
}
void print_number(int num){
  ... // Do things with int
}

// Assignment
struct person someotherguy = someguy;
int y = x;

// Operations
int ageDiff = someotherguy.age - someguy.age;
int z = x - y;
&lt;/pre&gt;

&lt;h2&gt;Tidying up with typedef&lt;/h2&gt;
&lt;p&gt;If you'd like to eliminate the verbosity of using &lt;code&gt;struct person&lt;/code&gt; every time 
you're working with a person structure, you can use &lt;code&gt;typedef&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;typedef works like so:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
typedef datatype newDataTypeName
&lt;/pre&gt;

&lt;p&gt;For example,&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Using typedef
#include&amp;lt;stdio.h&amp;gt;

typedef int WholeNumber;

int main(){
  WholeNumber x = 10;
  printf("%d is a whole number\n", x);
  return 0;
}
&lt;/pre&gt;

&lt;p&gt;While this example isn't particularly useful, it lets you understand how 
typedef works. &lt;/p&gt;
&lt;p&gt;Note again that &lt;code&gt;struct person&lt;/code&gt; behaves like any other data 
type, so the entire structure declaration can be used as the &lt;code&gt;datatype&lt;/code&gt; 
parameter of typedef. This really cleans up structure usage.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Using typedef
#include&amp;lt;stdio.h&amp;gt;

typedef struct product{
  char *label;
  int value;
} product_t;

int main(){
  product_t cookie; // Was formerly struct product cookie
  cookie.label = "wonderful cookie";
  cookie.value = 1;

  printf("The %s is $%d\n", cookie.label, cookie.value);
  return 0;
}

&lt;/pre&gt;

&lt;p&gt;Looking again at the usage of typedef (&lt;code&gt;typedef datatype newDataTypeName&lt;/code&gt;), we
see that &lt;code&gt;struct product{..}&lt;/code&gt; is the datatype, and &lt;code&gt;Product&lt;/code&gt; is the 
&lt;code&gt;newDataTypeName&lt;/code&gt;. We can now use &lt;code&gt;product_t&lt;/code&gt; in place of &lt;code&gt;struct product&lt;/code&gt;.
This includes variable assignments, function parameters, everything. (Note
that &lt;code&gt;product_t&lt;/code&gt; is read "product type", and structures generally follow this
naming convention.)&lt;/p&gt;
&lt;h2&gt;Applying typedef&lt;/h2&gt;
&lt;p&gt;With our newfound knowledge of typedef, lets implement it into our first
program. (This is definitely a code snippet I would attempt to type from 
memory)&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
// Using structures in C
#include&amp;lt;stdio.h&amp;gt;

// Struct declaration
typedef struct person{
  char *name;
  int age;
  char gender;
} person_t;

void print_person(person_t);

int main(){

  // Declaring a variable of type `person_t`
  person_t someguy;
  someguy.name = "Joseph";
  someguy.age = 21;
  someguy.gender = 'M';

  // Print person information
  print_person(someguy);

  return 0;
}

// Print a person's information
void print_person(person_t p){
  printf("Name: %s\n", p.name);
  printf("Age: %d\n", p.age);
  printf("Gender: %c\n", p.gender);
}


&lt;/pre&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Structures are great for representing collections of related attributes, and
they take very little effort to use! We'll cover more involved uses of
structures, such as arrays of structures and pointers to structures, in an
upcoming post.&lt;/p&gt;</content:encoded>
</item>

<item>
  <title>Converting a simple website to Python Flask</title>
  <link>http://vertstudios.com/blog/new-flask-site</link>
  <pubDate>Mon, 09 Jul 2012 10:17:00 +0000</pubDate>
  <description>Documenting first impressions converting a simple PHP/Wordpress
site to Python Flask.</description>
  <content:encoded>&lt;h1&gt;&lt;a href="/blog/new-flask-site"&gt;Converting a simple website to Python Flask&lt;/a&gt;&lt;/h1&gt;
    
&lt;p&gt;&lt;a href="http://flask.pocoo.org/"&gt;Flask&lt;/a&gt; is a Python web framework that's steadily
increasing in popularity within the webdev world. After reading so many 
great things about Flask, I decided to try it out myself. I personally find 
testing out a new framework difficult, because you must find a project complex 
enough to reveal the framework's quirks, but not so daunting as to take the 
fun out of the project. Luckily, my PHP/Wordpress powered website filled this
role quite nicely - the website simply consists of static content, a contact
page, and a blog. If I could not convert such a simple site over to Flask, 
I would immediately know that Flask and I would not make a good team.&lt;/p&gt;
&lt;p&gt;Spoiler alert: You're reading this on a Flask powered site! Feel free to 
check out the source of this site 
&lt;a href="https://github.com/joequery/Vert-Flask"&gt;on Github&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Getting Started&lt;/h2&gt;
&lt;p&gt;The first task at hand was simply getting the home, about, services, and work
pages to render correctly. While the task consisted mostly of copying and 
pasting, I was able to immediately apply most of the concepts from the
&lt;a href="http://flask.pocoo.org/docs/quickstart"&gt;Flask quickstart guide&lt;/a&gt;. Specifically, I had to learn&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;How do I actually start the server?&lt;/li&gt;
&lt;li&gt;Where do my templates go?&lt;/li&gt;
&lt;li&gt;Where do my static assets go?&lt;/li&gt;
&lt;li&gt;How do I retrieve my assets from within the templates?&lt;/li&gt;
&lt;li&gt;How do I route requests?&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Sure enough, getting the pure HTML documents to render was pretty simple.
By pure HTML, I mean there were no includes for headers, footers, etc. Thus 
the logical next step was to take these pure HTML documents and DRY up the 
repeating areas.&lt;/p&gt;
&lt;h2&gt;Using Jinja2&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;UPDATE&lt;/strong&gt;: Turns out I was just being dumb. The include statements 
&lt;a href="https://github.com/joequery/Vert-Flask/tree/master/templates"&gt;work fine&lt;/a&gt;.
&lt;/p&gt;&lt;div class="hr"&gt;&lt;hr/&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://jinja.pocoo.org/docs/"&gt;Jinja2&lt;/a&gt;, Flask's default templating engine, 
uses &lt;a href="http://jinja.pocoo.org/docs/templates/#template-inheritance"&gt;template inheritance&lt;/a&gt; in additon to supporting includes. To 
demonstrate, suppose we have a parent template &lt;code&gt;layout.html&lt;/code&gt; &lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
  &amp;lt;head&amp;gt;&amp;lt;title&amp;gt;My Website&amp;lt;/title&amp;gt; &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
  &amp;lt;div id="wrapper"&amp;gt;
    &amp;lt;div id="content"&amp;gt;
      {% block body %}{% endblock body %}
    &amp;lt;/div&amp;gt;&amp;lt;!--content--&amp;gt;
  &amp;lt;/div&amp;gt;&amp;lt;!--wrapper--&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;

&lt;p&gt;And a child template &lt;code&gt;index.html&lt;/code&gt; that inherits the parent and fills in its
blocks&lt;/p&gt;
&lt;pre class="prettyprint"&gt;{% extends "layout.html" %}
{% block body %}
  Body content goes here!
{% endblock body %}
&lt;/pre&gt;

&lt;p&gt;If we were to call &lt;a href="http://flask.pocoo.org/docs/quickstart/#rendering-templates"&gt;render_template&lt;/a&gt; on &lt;code&gt;index.html&lt;/code&gt;, this is what we
would get.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
  &amp;lt;head&amp;gt;&amp;lt;title&amp;gt;My Website&amp;lt;/title&amp;gt; &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
  &amp;lt;div id="wrapper"&amp;gt;
    &amp;lt;div id="content"&amp;gt;
      Body content goes here!
    &amp;lt;/div&amp;gt;&amp;lt;!--content--&amp;gt;
  &amp;lt;/div&amp;gt;&amp;lt;!--wrapper--&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;include&lt;/code&gt; statement works similarly to PHP's &lt;code&gt;include&lt;/code&gt; statement in regards
to importing files that render markup. Consider the footer for this site, 
located in &lt;code&gt;templates/includes/footer.html&lt;/code&gt;:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
&amp;lt;div id="footer"&amp;gt;
  &amp;lt;div class="hr"&amp;gt;&amp;lt;hr /&amp;gt;&amp;lt;/div&amp;gt;
  &amp;lt;p&amp;gt;
    &amp;lt;a href="mailto:hi@vertstudios.com"&amp;gt;hi@vertstudios.com&amp;lt;/a&amp;gt; |
    &amp;lt;a href="http://www.twitter.com/vertstudios"&amp;gt;@vertstudios&amp;lt;/a&amp;gt;
  &amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/pre&gt;

&lt;p&gt;And &lt;code&gt;templates/layout.html&lt;/code&gt;:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
  {% include "includes/meta_and_css.html" %}
  &amp;lt;body onload="prettyPrint()" id="{{g.bodyID}}"&amp;gt;
&amp;lt;div id="wrapper"&amp;gt;
  {% include "includes/nav.html" %}
  &amp;lt;div id="content"&amp;gt;
    {% block body %}{% endblock body %}
  &amp;lt;/div&amp;gt;&amp;lt;!--content--&amp;gt;
  {% include "includes/footer.html" %}
&amp;lt;/div&amp;gt;&amp;lt;!--wrapper--&amp;gt;
{% include "includes/javascripts.html" %}
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;

&lt;h2&gt;Being 'Brave'&lt;/h2&gt;
&lt;p&gt;Flask didn't always have an out-of-the-box solution to the problem at hand. In 
fact, it &lt;em&gt;rarely&lt;/em&gt; did. Flask did, however, give me all the tools necessary to 
create whatever I wanted. In a way, I felt that Flask itself was telling me
"Joseph, you're smart enough to implement X functionality on your own... be 
brave for once!"&lt;/p&gt;
&lt;p&gt;Sometimes reinventing the wheel is a rewarding exercise. &lt;/p&gt;
&lt;h2&gt;The Contact Form&lt;/h2&gt;
&lt;p&gt;The recommended method of dealing with forms in Flask is the &lt;a href="http://packages.python.org/Flask-WTF/"&gt;Flask-WTF&lt;/a&gt;
extension. Flask-WTF has many &lt;a href="http://flask.pocoo.org/docs/patterns/wtforms/#the-forms"&gt;built in validation methods&lt;/a&gt;, but it did not
include validation for a phone number. No big deal, any form library worth its
salt has means for defining custom validation functions. WTForms does in fact
have a mechanism for implementing &lt;a href="http://wtforms.simplecodes.com/docs/1.0.1/validators.html"&gt;custom validators&lt;/a&gt;, but I did not find 
their examples very pleasing to the eye:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
def length(min=-1, max=-1):
    message = 'Must be between %d and %d characters long.' % (min, max)

    def _length(form, field):
        l = field.data and len(field.data) or 0
        if l &amp;lt; min or max != -1 and l &amp;gt; max:
            raise ValidationError(message)

    return _length

class MyForm(Form):
    name = TextField('Name', [Required(), length(max=50)])
&lt;/pre&gt;

&lt;p&gt;Consequently, I used Flask-WTF to gather data from the form fields, but I 
rolled my own validation module, which only took about an hour. &lt;/p&gt;
&lt;p&gt;The actual sending of the email was easily handled with Python's built-in
&lt;code&gt;smtplib&lt;/code&gt; module and Gmail.&lt;/p&gt;
&lt;h2&gt;The Blog&lt;/h2&gt;
&lt;p&gt;Creating a blog has become the "Hello, World" of web application frameworks.
While &lt;a href="http://wiki.python.org/moin/PythonBlogSoftware"&gt;Python blogging software&lt;/a&gt; does exist, it seemed like it would take
longer to integrate an existing blogging platform into my Flask project than
just rolling my own. &lt;/p&gt;
&lt;p&gt;For the past year or so, I've longed for a file-system based blogging platform.
Writing my articles in VIM + Markdown is &lt;strong&gt;so&lt;/strong&gt; much more enjoyable than
writing HTML in VIM, moving the HTML over to Wordpress, previewing the HTML, 
making sure the formatting is right, and other annoying steps. &lt;/p&gt;
&lt;p&gt;There were a few specific things I needed to accomplish with the blog:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Ability to generate an RSS feed&lt;/li&gt;
&lt;li&gt;The URLs of the blog posts must be the same as before.&lt;/li&gt;
&lt;li&gt;Pagination&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Without the need to generate an RSS feed, the only thing I would need to do is
route &lt;code&gt;/blog/&amp;lt;post&amp;gt;/&lt;/code&gt; to a function that attempts to render a template 
named &lt;code&gt;/blog/the-post-url&lt;/code&gt;, and return a 404 if that template isn't found. 
The RSS requirement, however, forced me to think how I should go about storing
the meta data for each post.&lt;/p&gt;
&lt;p&gt;I settled on a fairly simple structure that, while not beautiful or clever,
works good enough for me. I create a directory in &lt;code&gt;/blog/posts/&lt;/code&gt; named &lt;code&gt;desired
-post-url&lt;/code&gt;. Within that directory, I create two files: &lt;code&gt;meta.py&lt;/code&gt; and &lt;code&gt;body.html&lt;/code&gt;. &lt;code&gt;meta.py&lt;/code&gt; just contains a few variables for metadata (date posted, excerpt, 
etc), and body.html has the post body. &lt;/p&gt;
&lt;p&gt;To avoid having to parse through all the metadata files to figure out the
order of the posts for the RSS feed, I just prepend the directory name to the
top of a file called &lt;code&gt;rss.txt&lt;/code&gt;. Again, not the most beautiful thing in the 
world but it's a system that I find easy to understand and easy to work with.&lt;/p&gt;
&lt;p&gt;The RSS feed and blog pagination are handled in the same step. I run a script
called &lt;code&gt;genfeed.py&lt;/code&gt; which creates the rss xml file and pagination files.
Using static files generated by the &lt;code&gt;geenfeed.py&lt;/code&gt; script (which reads the
&lt;code&gt;rss.txt&lt;/code&gt; script mentioned earlier) for pagination makes sense because the
pagination should only change whenever I update/create a story. &lt;/p&gt;
&lt;h3&gt;Importing my Blog Posts&lt;/h3&gt;
&lt;p&gt;To import my Wordpress posts into this new structure, all I had to do was
parse Wordpress's export xml file with &lt;a href="http://packages.python.org/pyquery/api.html"&gt;PyQuery&lt;/a&gt; and create the files with
standard library functions. I didn't bother to convert the posts from Wordpress
to Markdown, so all old posts you look through in the source will have normal
HTML.&lt;/p&gt;
&lt;h2&gt;Structural Troubles&lt;/h2&gt;
&lt;p&gt;One of the biggest troubles I faced throughout the site development was how
to import things into particular files. This &lt;a href="http://stackoverflow.com/a/9123510/670823"&gt;StackOverflow answer&lt;/a&gt; 
describes the steps necessary to import a module in a parent/sibling directory
when running a script directly. Consequently, any scripts that needed access to
the &lt;code&gt;app&lt;/code&gt; object (which holds a lot of important methods and attributes about
the application instance), I had to either run 
&lt;code&gt;python -m mywebsite.blog.genfeed&lt;/code&gt;, or just move &lt;code&gt;genfeed.py&lt;/code&gt; to the same
directory as &lt;code&gt;mywebsite.py&lt;/code&gt;, which would enable me to run &lt;code&gt;python genfeed.py&lt;/code&gt;. 
I chose the latter out of sheer laziness, though I'm not particularly happy
I had to make such a choice. I should note that this is not a Flask specific 
issue, but a Python issue.&lt;/p&gt;
&lt;h2&gt;Development vs Production Environment&lt;/h2&gt;
&lt;p&gt;In development, all assets are served from the static files. In production,
all assets are served from S3. The environment is set by a env-var called
&lt;code&gt;FLASK_ENV&lt;/code&gt;. I needed a way to let my templates know "Hey, you're in the
production environment, you should link to S3 files instead of static files!".
I decided to take advantage of Flask's &lt;code&gt;g&lt;/code&gt; object, which is a global object
that exists througout the request context. You're free to populate it with
whatever you want. I created and used the property &lt;code&gt;g.assets&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;While this suited my needs perfectly, it caused my templates to appear 
slightly less pretty. Anytime I wanted to call a macro that looks for the 
&lt;code&gt;g.assets&lt;/code&gt; property, I'd have to pass &lt;code&gt;g&lt;/code&gt; to it. For example,
here's the definition of the &lt;code&gt;img&lt;/code&gt; macro, a function used to render images
on the site:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
{% macro img(g, file, alt="", class="") %}
&amp;lt;img 
  src="{{g.assets}}/images/{{file}}" 
  alt="{{alt}}" 
  class="{{class}}" 
  /&amp;gt;
{% endmacro %}
&lt;/pre&gt;

&lt;p&gt;An example call to the macro:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
{{img(g, "pointer.png", "", "pointer")|safe }}
&lt;/pre&gt;

&lt;p&gt;It's more verbose than what I'd really like, but it gets the job done.&lt;/p&gt;
&lt;h2&gt;Going Live with Nginx and uWSGI&lt;/h2&gt;
&lt;p&gt;Now that my project was pretty much finished, it was time to put the files
on my Linode VPS and show my project to the world! I decided to use Nginx with
uWSGI, simply because the pair have been the subject of many tutorials. Flask
itself &lt;a href="http://flask.pocoo.org/docs/deploying/uwsgi/"&gt;has documentation&lt;/a&gt; on uWSGI. However, I found parts of the
documentation inadequate.&lt;/p&gt;
&lt;p&gt;From the documentation:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
# Given a flask application in myapp.py, use the following command:
$ uwsgi -s /tmp/uwsgi.sock --module myapp --callable app
&lt;/pre&gt;

&lt;p&gt;If you want to put a project on a live server, there's no way you should have
to do so much work! uWSGI has &lt;a href="http://projects.unbit.it/uwsgi/wiki/INIFiles"&gt;ini configuration files&lt;/a&gt; that I took full
advantage of. Now, instead of executing a verbose command from the shell, I can
simply execute&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
$ uwsgi uwsgi.ini
&lt;/pre&gt;

&lt;p&gt;My &lt;code&gt;uwsgi.ini&lt;/code&gt; is as follows:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
[uwsgi]
project = vertstudios
daemonize = /var/log/nginx/access.log
master = true
chdir = /var/www/vertstudios.com
socket = 127.0.0.1:5000
wsgi = %(project):variable holding app instance
virtualenv = env/
pidfile = /var/run/uwsgi/%(project).pid 
touch-reload  = /var/run/uwsgi/%(project).pid  
processes = 3 
procname-prefix = %(project)
&lt;/pre&gt;

&lt;p&gt;Now my uWSGI configuration is under version control with the rest of my project.&lt;/p&gt;
&lt;p&gt;Here's an explanation for the parameters:  &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;project: The module name where you call &lt;code&gt;app.run()&lt;/code&gt;.  &lt;/li&gt;
&lt;li&gt;daemonize: If you want to daemonize. For some reason, you have to specify a 
             log file path or uWSGI will just shove things down &lt;code&gt;stdin&lt;/code&gt;. &lt;code&gt;true&lt;/code&gt;
             did not work for me.&lt;/li&gt;
&lt;li&gt;master: Boolean indicating if you want a master process. Master processes
         make &lt;a href="http://projects.unbit.it/uwsgi/wiki/Management"&gt;uwsgi management&lt;/a&gt; &lt;em&gt;much&lt;/em&gt; easier.&lt;/li&gt;
&lt;li&gt;chdir: Change directory. Essentially lets you keep parameters such as 
       "project" and virtualenv relative to the path provided to chdir.&lt;/li&gt;
&lt;li&gt;socket: A Unix socket path or TCP socket info&lt;/li&gt;
&lt;li&gt;wsgi: %(the module containing app):app&lt;/li&gt;
&lt;li&gt;virtualenv: Path to the virtualenv for the project.&lt;/li&gt;
&lt;li&gt;pidfile: Where the master process pid file will be written.&lt;/li&gt;
&lt;li&gt;touch-reload: Touching this file causes the processes to reload (convenient!)&lt;/li&gt;
&lt;li&gt;processes: How many processes you want running (not including master process)&lt;/li&gt;
&lt;li&gt;procname-prefix: Process name prefix. Useful for &lt;code&gt;ps aux | grep myapp&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Now, for the parts of my nginx config relevant to uWSGI:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
# Redirect everything to the main site.
server {
  server_name www.vertstudios.com;
  return 301 http://vertstudios.com$request_uri;
}

server {
  server_name vertstudios.com;
  location / { try_files $uri @flaskapp; }
  location @flaskapp {
    include uwsgi_params;
    uwsgi_pass 127.0.0.1:5000;
  }
}
&lt;/pre&gt;

&lt;h2&gt;Things left TODO&lt;/h2&gt;
&lt;p&gt;I felt I had done enough to merit scrapping my PHP/Wordpress site and put the
Flask site up in its place. Despite that, there's still quite a bit of work to
be done.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;I plan on exporting my Wordpress comments to Disqus. I enjoy interacting with 
people that read my articles, and I'd like to preserve the comments I've 
already acquired.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;I've managed to break a few links. In particular, I've broken links to php
files I stupidly used to demo some of my jQuery plugins.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Using &lt;a href="http://google-code-prettify.googlecode.com/svn/trunk/README.html"&gt;prettify&lt;/a&gt; for syntax highlighting means I have to still use &amp;lt;pre&amp;gt;
tags in my documents, since the script requires a class of "prettyprint" on
those tags. I'll either adjust prettyprint js and styles myself, find an 
alternative syntax highlighter, or do some processing of the markup to append
the "prettyprint" class whenever it finds the &amp;lt;pre&amp;gt; tag.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Still need to set up git deployment. I'm currently just pulling from a 
private bitbucket repo on my server.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;I need to automate my build workflow. A single bash script should concat all
my CSS/JS files, run YUICompressor, and upload the files to S3.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;I really need to implement meta description tags for my posts...but that
  would require me to actually write them.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Overall Impressions&lt;/h2&gt;
&lt;p&gt;As a whole, I'm quite pleased with Flask. For the most part, it gets out of
your way and lets you build things how you want to build them. Consequently,
your project structure may be sloppy (especially when first learning Flask),
but you're guaranteed to understand how and why everything works.&lt;/p&gt;</content:encoded>
</item>

<item>
  <title>Markdown to PDF Utility</title>
  <link>http://vertstudios.com/blog/markdown-pdf-utility</link>
  <pubDate>Thu, 03 May 2012 22:57:00 +0000</pubDate>
  <description>I needed to get a Markdown document in PDF format. Unable to find a good solution, I set off to make a Markdown to PDF conversion utility. About 20 lines of Python later, here we are!</description>
  <content:encoded>&lt;h1&gt;&lt;a href="/blog/markdown-pdf-utility"&gt;Markdown to PDF Utility&lt;/a&gt;&lt;/h1&gt;
    

I needed to get a Markdown document in PDF format. Unable to find a good solution, I set off to make a Markdown to PDF conversion utility. About 20 lines of Python later, here we are!

&lt;h2&gt;md2pdf: Markdown to PDF&lt;/h2&gt;

You can download &lt;a href="https://github.com/joequery/md2pdf"&gt;md2pdf&lt;/a&gt; on Github. Installation instructions can be found in the README. Usage is extremely simple:

&lt;pre class="prettyprint"&gt;
$ md2pdf my-markdown-document.md
&lt;/pre&gt;

&lt;h2&gt;How it was made&lt;/h2&gt;
This utility is actually pretty silly. It simply serves as a glue between
&lt;a href="http://code.google.com/p/python-markdown2/"&gt;markdown2&lt;/a&gt;, which takes Markdown and produces HTML, and &lt;a href="www.xhtml2pdf.com"&gt;xhtml2pdf&lt;/a&gt;, which takes HTML and produces PDFs. The script uses a system call because the xhtml2pdf interface is non-trivial. Consequently, you're probably better off not using this on a production server.</content:encoded>
</item>

<item>
  <title>Ubuntu Screencast Software for 11.04+</title>
  <link>http://vertstudios.com/blog/ubuntu-screencast-software-11-04</link>
  <pubDate>Wed, 25 Apr 2012 05:07:00 +0000</pubDate>
  <description>I browsed Google for quite a while before I finally found a good product for recording screencasts on Ubuntu. Most software I found, no offense gtk-recordMyDesktop, was extremely outdated and hardly functional. Video quality was either terrible or video/audio was out of sync.</description>
  <content:encoded>&lt;h1&gt;&lt;a href="/blog/ubuntu-screencast-software-11-04"&gt;Ubuntu Screencast Software for 11.04+&lt;/a&gt;&lt;/h1&gt;
    

I browsed Google for quite a while before I finally found a good product for recording screencasts on Ubuntu. Most software I found, no offense gtk-recordMyDesktop, was extremely outdated and hardly functional. Video quality was either terrible or video/audio was out of sync.

&lt;h2&gt;Enter Kazam!&lt;/h2&gt;
Thanks to some more strict queries on Google, I found &lt;a href="http://www.twm-kd.com/linux/kazam/kazam-1-2-0-released-as-stable/"&gt;Kazam&lt;/a&gt; on &lt;a href="http://www.askubuntu.com"&gt;AskUbuntu.com&lt;/a&gt;. 

It has an extremely simple interface, as seen below.
&lt;img src="http://i.imgur.com/WhhVN.png" alt="Kazam Ubuntu Screencast Software"/&gt;

The quality is just fine for simple screencasts, and it allows you to record audio that actually syncs with the video! 

&lt;h2&gt;Installation&lt;/h2&gt;

First, we need some Python modules to be installed.
&lt;pre class="prettyprint"&gt;
$ sudo apt-get install --reinstall gir1.2-gtk-2.0 python-software-properties software-properties-gtk
&lt;/pre&gt;

Now we actually grab Kazam as instructed by their site.
&lt;pre class="prettyprint"&gt;
$ sudo add-apt-repository ppa:kazam-team/stable-series
$ sudo apt-get update
$ sudo apt-get install kazam
&lt;/pre&gt;

And you're done! You can run kazam via the command line or your distro's menu. 

&lt;h2&gt;Extras&lt;/h2&gt;
If you happen to have FFMpeg installed, here's a nice 2-pass video/audio &lt;a href="https://gist.github.com/2486369"&gt;encoder script&lt;/a&gt; that encodes with H.264.</content:encoded>
</item>

<item>
  <title>VI Keybindings in your Shell</title>
  <link>http://vertstudios.com/blog/vi-keybindings-shell</link>
  <pubDate>Wed, 25 Apr 2012 03:52:00 +0000</pubDate>
  <description>There was once a very sad point in my development career where if I made a typo earlier in one of my bash statements, I would have to hold the left arrow to get my cursor over to the problem area and fix it. Then, one fateful day, I discovered VI keybindings in the shell!</description>
  <content:encoded>&lt;h1&gt;&lt;a href="/blog/vi-keybindings-shell"&gt;VI Keybindings in your Shell&lt;/a&gt;&lt;/h1&gt;
    

There was once a very sad point in my development career where if I made a typo earlier in one of my bash statements, I would have to hold the left arrow to get my cursor over to the problem area and fix it. Then, one fateful day, I discovered VI keybindings in the shell!

&lt;h2&gt;Activating VI Keybindings&lt;/h2&gt;

To get VI keybindings working in your shell, simply execute

&lt;pre class="prettyprint"&gt;
$ set -o vi
&lt;/pre&gt;

(If you decide you like vi keybindings in the shell and you want this mode enabled upon shell startup, append the command to your ~/.bash_profile for OS X and ~/.bashrc for linux ((&lt;a href="http://www.joshstaiger.org/archives/2005/07/bash_profile_vs.html"&gt;Why the difference?&lt;/a&gt;))

&lt;h2&gt;Using the VI Keybindings&lt;/h2&gt;

The shell will have normal/insert mode as expected. Here are the commands I use frequently:

&lt;pre class="prettyprint"&gt;
i - enter insert mode
esc - back to normal mode

* IN NORMAL MODE *
cc - clear the current line and enter insert mode
 C - clear from cursor until the end of the line and enter insert mode
dd - delete the current line
 D - delete from the cursor until the end of the line
 w - next word
 W - next white-space delimited word
 b - previous word
 B - previous white-space delimited word
dw - delete word
cw - change word
fx - find the next occurrence of the character 'x'
Fx - find the previous occurrence of the character 'x'
 $ - move the cursor to the end of the line
 0 - move the cursor to the beginning of the line
 ; - repeat last find command (preserves direction)
 l - move cursor right
 h - move cursor left
 k - scroll up through command history
 j - scroll down through command history
 A - move the cursor to the end of the line and enter insert mode
 I - move the cursor to the beginning of the line and enter insert mode

* Numeric modifier keys work as well! *
5W - move forward five white-space delimited words. 

&lt;/pre&gt;</content:encoded>
</item>

</channel>
</rss>
