Let's break it down a bit.
if( ! ( st_cur = (struct ST_info *) malloc(sizeof( struct ST_info ) ) ) )
{
perror( "malloc failed" );
return( 1 );
}
Is equivalent to:
struct ST_info * st_cur = NULL;
//...
/* Assign heap memory of native byte size equal to that
* of struct ST_info and save a pointer to the allocated
* memory. */
st_cur = malloc( sizeof( struct ST_info ) );
/* If the malloc succeeded it will have returned a valid
* pointer to some part of the heap, otherwise it returns
* NULL so we check for NULL here. */
if (st_cur == NULL) {
/* Print a relevant error message to stderr. */
perror("malloc failed");
/* Return a non-zero value to indicate that something failed. */
return(1);
}
If you later wish to free the memory, which one should do for all dynamically allocated memory before finishing a program, you can use free()
. here you do not need to first check for NULL
as A) the if
above should have caught it, and B) if passed NULL
then free
safely does nothing.
malloc
can fail due to the system not being able to allocate the amount of memory requested. If the size passed to malloc
is zero then the return value is implementation dependent but the returned pointer shall not be dereferenced.
Additionally, it has become good practice to not explicitly cast the value returned by malloc
, thus
st_cur = (struct ST_info *) malloc(sizeof( struct ST_info ) )
becomes
st_cur = malloc(sizeof( struct ST_info ) )