Monday, September 24, 2012

String storage allocation tutorial

This program extracted from C tutorial by Mark  Burgess didn't completely work in Mingw gcc v 4.5.2.
It worked up to the last printf statement.
I don't understand it but it shows the incompatibilities among different C compilers.

/******************************************************/
/*                                                    */
/* String storage allocation                          */
/*                                                    */
/******************************************************/

#include <stdio.h>

/* #include another file for malloc() and   */
/* strlen() ???. Check the compiler manual! */

#define NOOFSTR   3
#define BUFSIZE   255
#define CODE      0

/******************************************************/
/* Level 0                                            */
/******************************************************/


main ()

{ char *array[NOOFSTR], *malloc();
  char buffer[BUFSIZE];
  int i;

printf ("Total no of string to enter=%d\n",NOOFSTR);
for (i = 0; NOOFSTR ; i++)
   {
   printf ("Enter string %d :",i);
   scanf  ("%255s",buffer);

   array[i] = malloc(strlen(buffer)+1);

   if (array[i] == NULL)
      {
      printf ("Can't allocate memory\n");
      QuitSafely (array);
      }

   strcpy (array[i],buffer);
   printf ("%s\n",array[i]);
   }
printf ("%s\n",array[0]);
/*
for (i = 0; i < NOOFSTR; i++)
   {
   printf ("%s\n",array[i]);
   }
*/
QuitSafely(array);
}

/******************************************************/
/* Snakes & Ladders!                                  */
/******************************************************/

QuitSafely (array)       /* Quit & de-alloc memory */

char *array[NOOFSTR];

{ int i, len;

for (i = 0; i < NOOFSTR; i++)
   {
   len = strlen(array[i]) + 1;
    free(array[i]);
/*
    gcc free is of void type so cannot return any value.
    if (free (array[i]) != 0)
      {
      printf ("Debug: free failed\n");
      }
*/
      }

exit (CODE);
}

               /* end */

No comments:

Post a Comment