This is a discussion on Memory Functions - Still Learning within the C Programming forums, part of the General Programming Boards category; Originally Posted by tabstop Whenever you ask yourself "How many of these do I need?" and your answer is "I ...
Code:int num; int* pNum; pNum = malloc( sizeof(int) ); /* Assigning the pointer address. */ num = 5; *pNum = 10; /* Assigning a value to the address stored in the pointer. */ free( pNum );
Until you can build a working general purpose reprogrammable computer out of basic components from radio shack, you are not fit to call yourself a programmer in my presence. This is cwhizard, signing off.
But of course in real code (not just an example) you'd want to save the result of realloc() to a temporary pointer first and check if it's NULL, otherwise you could have a memory leak if you overwrite your pointer with NULL without freeing it first.Code:int* pNums = malloc( sizeof(int) ); /* An array of 1 int. */ pNums = 5; pNums = realloc( pNums, 3 * sizeof(int) ); /* Now it can hold 3 ints. */ pNums = 10; pNums = 666;
Yes, you need to realloc() there, otherwise you'll be writing off the end of your array into memory that doesn't belong to that variable.
It's like trying to pour 3 cups of coffee into 1 coffee cup. First you need to get 2 more cups, otherwise you'll just make a big mess.