Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*============================================================================
- ----------------------------------------------------------------------------
- pointerAlloc.c - Pointer Allocation (and manipulation (like arrays)).
- (c) Damion 'Phr0z3n.Dev' Tapper, 2013.
- Email: Phr0z3n.Dev@Gmail.com
- ----------------------------------------------------------------------------
- ============================================================================*/
- #define USE_SEC_API /* Comment this line if you do not have the secure libraries. */
- #include <stdio.h>
- #include <stdlib.h> /* For calloc... better than malloc IMHO. */
- struct tempS
- {
- char *myString;
- }*tsp; /* A pointer to a structure. */
- int main(void)
- {
- /* Pre-allocation of memory for a pointer. */
- tsp = calloc(1, sizeof(struct tempS));
- /* In this case, the pointer is operating like an array or any other non-pointer variable. */
- /* This method also gives C a similar functionality to the 'new' keyword in C++. */
- /* This also voids the need for the creation of a non-pointer variable to equate the pointer to in order to initialize it. */
- #ifdef USE_SEC_API
- /* CHECK 1: */
- printf_s("%d\n", sizeof(tsp)); /* The secure printf function (good programming practice). */
- tsp->myString = "Hello Secure World!";
- /* CHECK 2: */
- printf_s("%d\n", sizeof(tsp)); /* This should reveal a little magic about the versatility of the method we are using. */
- printf_s("%s\n", tsp->myString);
- #else
- /* If you are lacking the secure libraries. */
- /* CHECK 1: */
- printf("%d\n", sizeof(tsp));
- tsp->myString = "Hello World!";
- /* CHECK 2: */
- printf("%d\n", sizeof(tsp));
- printf("%s\n", tsp->myString);
- #endif
- /* This is the tricky bit. */
- free(tsp);
- /* This actually eradicates any trace of the pointer from memory. */
- /* Make careful note that this cannot be done with arrays which makes pointers superior in this case. */
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement