SHARE
TWEET

Pointer Allocation (and manipulation (like arrays))

Phr0zen_Penguin Nov 16th, 2013 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*============================================================================
  2.   ----------------------------------------------------------------------------
  3.   pointerAlloc.c - Pointer Allocation (and manipulation (like arrays)).
  4.                  (c) Damion 'Phr0z3n.Dev' Tapper, 2013.
  5.                  Email: Phr0z3n.Dev@Gmail.com
  6.   ----------------------------------------------------------------------------
  7.   ============================================================================*/
  8. #define USE_SEC_API /* Comment this line if you do not have the secure libraries. */
  9.  
  10. #include <stdio.h>
  11. #include <stdlib.h> /* For calloc... better than malloc IMHO. */
  12.  
  13. struct  tempS
  14. {
  15.         char    *myString;
  16. }*tsp; /* A pointer to a structure. */
  17.  
  18. int main(void)
  19. {
  20.         /* Pre-allocation of memory for a pointer. */
  21.         tsp = calloc(1, sizeof(struct tempS));
  22.         /* In this case, the pointer is operating like an array or any other non-pointer variable. */
  23.         /* This method also gives C a similar functionality to the 'new' keyword in C++. */
  24.         /* This also voids the need for the creation of a non-pointer variable to equate the pointer to in order to initialize it. */
  25.  
  26. #ifdef USE_SEC_API
  27.         /* CHECK 1: */
  28.         printf_s("%d\n", sizeof(tsp)); /* The secure printf function (good programming practice). */
  29.  
  30.         tsp->myString = "Hello Secure World!";
  31.  
  32.         /* CHECK 2: */
  33.         printf_s("%d\n", sizeof(tsp)); /* This should reveal a little magic about the versatility of the method we are using. */
  34.  
  35.         printf_s("%s\n", tsp->myString);
  36. #else
  37.         /* If you are lacking the secure libraries. */
  38.         /* CHECK 1: */
  39.         printf("%d\n", sizeof(tsp));
  40.  
  41.         tsp->myString = "Hello World!";
  42.  
  43.         /* CHECK 2: */
  44.         printf("%d\n", sizeof(tsp));
  45.  
  46.         printf("%s\n", tsp->myString);
  47. #endif
  48.  
  49.         /* This is the tricky bit. */
  50.         free(tsp);
  51.         /* This actually eradicates any trace of the pointer from memory. */
  52.         /* Make careful note that this cannot be done with arrays which makes pointers superior in this case. */
  53.  
  54.         return 0;
  55. }
RAW Paste Data
Top