Allocating on the Stack

While looking at various websites about dealing with memory fragmentation, I came by another useful function that I didn’t know about called alloca(). This function allocates memory on the stack, and so does not need to be freed, and only exists in the scope that it is in.

Here is an example.

// --- [ includes ] -------------------------------------------
//
#include <alloca.h>
#include <string.h>
#include <stdio.h>
 
// --- [ entry point ] ----------------------------------------
//
void main()
{
	char * pTestText = static_cast<char *>( alloca( 100 ) );
 
	strncpy( pTestText, "Testing :)\n", 100 );
 
	printf( pTestText );
}

 

The alloca() function works just like malloc(), only of course returning memory that is on the stack. This can be potentially bad for memory stomping, since pointers in the local scope could be altered if you go outside of the stack allocated.

I’m trying to always use the version of strings that are safe, since they has the potential to go wrong if a string doesn’t have a null character.