All pastes #1975181 Raw Edit

Untitled

public c v1 · immutable
#1975181 ·published 2010-10-28 01:17 UTC
rendered paste body
#include "stdio.h"#include "stdlib.h"int main(int argc, char **argv){    int *x = NULL;    if (!x)        printf("x does not point to a useful variable, so the 'variable' we're after is effective non-existent\r\n");    /* Let's allocate an int for x to point to! */    x = malloc(sizeof(*x));    /* Uh oh. */    if (x == NULL)    {        printf("Oops, got an error on malloc. Recovery from this is beyond the scope of this example program. :)\r\n");        return EXIT_FAILURE;    }    /* Yay, x points to a value we can use now. Kinda. */    printf("Wewt, x points to an int now, but on my system malloc doesn't explicitely clear the memory so it's effectively uninitialized. :(\r\n");    printf("Just for kicks, the value of *x is: %d \r\n", *x);    /* Let's do the sane thing and initialize our variable to a known safe value.  */    *x = 0;    /* Now we're at a point where we can a) test for the 'existence' of a usable value and b) use that value. */    /* Everytime we do this, we have to first check whether x is NULL (indicating no variable exists) or else       we run the risk of creating a segmentation fault by derefencing an invalid pointer. We also have to make       sure we free the memory pointed to by x when we're done with it, else we'll have a memory leak on our hands.       Additionally, we have to remember to set x to NULL after we free the memory, so that x doesn't continue to       point at memory we has no business accessing, AND so that we can properly test for 'existence'. Shit. That's       a lot of work. :( */    if (x)    {        *x += 5;        printf("*x is now: %d\r\n", *x);    }    /* We're done with the memory, let's free it. */    free(x);    x = NULL;    return EXIT_SUCCESS;}