There are numerous situations when we need to allocate memory - particularly when the size of said storage is not known at time of coding.  As with file I/O (i.e., where 'fopen()' fails to gain access to a file), we need to error-check if a request for memory fails.  And it behooves us to assure the requested memory is FREED when no longer needed.




(right-click to download)

/* pgm22 source */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum usecode {RET_ERR = -1, RET_OK};

int reverse_str(char *);     // our reusable function to reverse the chars in a string

int main(void) {
     char sentence[80];     // we might use a longer string;  80 is enough for here

     // shorter string
     strcpy(sentence, "LOOK! A flying PIG!");

     // longer string
     // strcpy(sentence, "Cats & Dogs NEVER get along together, but Dogs are far better, eh?");

     printf("\nVariable 'sentence' before reversing:\n %s\n\n", sentence);

     if (reverse_str(&sentence[0]) == RET_ERR)

     printf("After reversing:\n %s\n\n", sentence);

/* NOTE: this is NOT the best solution for reversing */
/* the contents of a string. It's just ONE possibility */
int reverse_str(char source[])   {
     char *tmpstr;
     int     src_len;
     int     x;
     int     y;

     src_len = strlen(source);
     tmpstr = calloc(src_len + 1, sizeof(char)); // request memory from the operating system

     if (tmpstr == NULL) {
          printf("\nMemory allocation error!\n");

     for (x = src_len - 1, y = 0; y < src_len; y++)    // article has more details on this loop
          *(tmpstr + x--) = source[y];

     strcpy(source, tmpstr);

     free(tmpstr);       // good practice to FREE any memory we allocate