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


//   free- A lot of extra marks
//Avoid global variables.

struct packet { //struct for the packets
int source;
int destination;
int type;
int port;
char data[49];//starts at 0
};

int add(); //to add a packet
void view(); // view a created packet
void save(); // to save the packet/packets
int open(); // open saved packets


int main(){
struct packet* create; // packets can be stored
create = malloc(sizeof(struct packet));// the size is accordingly to the structure

int pack = 0, menu; //packets equal 0

        do{ //start of the code, enter a number 1-5 if not error message will appear
                printf("\n\n");
                puts("Please choose a number - ");
                puts("\t 1 - to add a packet.");
                puts("\t 2 - to view current packets.");
                puts("\t 3 - to Save the current packets.");
                puts("\t 4 - to Open the current packet file.");
                puts("\t 5 - to exit the program.");
                printf("Please choose one: ");

                scanf("%d", &menu); //Scan for menu choice

                switch(menu){
                         case 1 : pack = add(create, pack); //Calling the menu function
                                break;
                         case 2 : view(create, pack);
                                break;
                         case 3 : save(create, pack);
                                  printf("Saving %d packets. \n", pack);
                                break;
                         case 4 : open(create);
                                break;
                         case 5 : puts("Exit.");
                                break;
                         default:puts("ERROR! Please enter a valid choice");// the error messgae
                                 break;
                           }
                           create = realloc(create,(pack+1)*sizeof(struct packet));
}while (menu !=5); //if while is not equal to 5 you can choose other options
   return 0;
         }

  int add(struct packet *create, int pack){ // the funtion to add packets
int aflag=0; int bflag=0; int cflag=0;
  printf("\n\n");

     printf("Please enter a 4 digit source > ");
        scanf("%d", &create[pack].source);

          while (create[pack].source < 1 || (create[pack].source > 1024))
            {
            puts("Source too big");
            printf("Please enter a 4 digit source > ");
            scanf("%d", &create[pack].source);
            }

     printf("Please enter a 4 digit destination > ");
        scanf("%d", &create[pack].destination);
        while (create[pack].destination < 1 || (create[pack].destination > 1024))
            {
            puts("Destination too big");
            printf("Please enter your destination > ");
            scanf("%d", &create[pack].destination);
            }

      printf("Please enter your type below 10 > ");
        scanf("%d", &create[pack].type);

          while (create[pack].type < 1 || (create[pack].type > 10))
            {
            puts("type too big");
            printf("Please enter a 4 digit source > ");
            scanf("%d", &create[pack].type);
            }

     printf("Please enter a 4 digit port > ");
        scanf("%d", &create[pack].port);

          while (create[pack].port < 1 || (create[pack].port > 1024))
            {
            puts("Port too big");
            printf("Please enter your Port > ");
            scanf("%d", &create[pack].port);
            }


while (aflag!=1)

{
     printf("Please enter a data > ");
        scanf("%s", create[pack].data);
        int length=0;
        length = strlen(create[pack].data);


        if (length  > 50)
            {
            puts("Data too long");

            bflag=0;

            }
else
{
    bflag=1;

}

            int i=0;
        for(i=0;i<length;i++)
        {
            if(isalpha(create[pack].data[i]))
            {
                printf("\n Not all digits\n");
                cflag=0;
            }

            else
            {
                cflag=1;
            }
        }

if (bflag==1&&cflag==1)
    aflag=1;
}



        pack++;
        return pack;
}


void view(struct packet *create,int pack){ //funtion to view a packet
    int i=0; //if i is equal to 0 the error message will appear
if (pack == 0){ //checks if there's any packets in the database
    puts("No packets in the database.");//error message

}else //if there is packets in the database do this.
     printf("\n\nCurrently there are %d packets.", pack);
  for (i=0;i<pack;i++) {//count through the packets

    printf("\n______________________________"); //sections the code. Shows what you have entered for the source etc.
    printf("\nPacket number %d  \n\t", i+1);
    printf("Your source is      :%d. \n\t", create[i].source);
    printf("Your desintation is :%d. \n\t", create[i].destination);
    printf("Your type is        :%d. \n\t", create[i].type);
    printf("Your port is        :%d. \n\t", create[i].port);
    printf("Your data is        :%s. \n\t", create[i].data);
    printf("\n______________________________");
  printf("\n\n");
}
}


void save(struct packet *create,int pack){
      FILE *recordFile;                 //file handle
      char fileName[30] = { '\0'};      //string to store the file name
      int i;

      puts("Enter a filename to save the records :");   //ask the user for the filename
      scanf("%s", fileName);                            //store the filename: data input should be checked
                                                        //here in your program

      //try and open the file for writing and react accordingly if there is a problem
      if((recordFile = fopen(fileName,"w"))==NULL){
          printf("Couldn't open the file: %s\n",fileName);
          exit(1);
      }
      else{ //the file opened so print the records array of Person's to it
          for(i=0;i<pack;i++){
              fprintf(recordFile,"%d:%d:%d:%d:%s\n",
                create[i].source,
                create[i].destination,
                create[i].type,
                create[i].port,
                create[i].data);
          }
          fclose(recordFile);   //close the file
      }

}

int open(struct packet *create,int packs)
{
            FILE *recordfile;

            char file_location[40];
            char buf[1000];

            printf("\nPlease enter file name with '.txt'\n");
            scanf("%s" ,file_location);


            recordfile =fopen(file_location, "r");

            if (!recordfile)
            {
                printf("\nError\n");
                return 1;

            }


            while (fgets(buf,1000, recordfile)!=NULL)
            {
                printf("%s",buf);
            }
                fclose(recordfile);
                return 0;

    }

Bold Text HereHaving a bit mess around just to get my head around Malloc and Realloc. My code has no errors and everything seems to be working fine. What im wondering is, is the malloc and realloc actually wokring?

Without seeing the code, it's hard to tell. malloc and realloc will return NULL on failure, but there are gotchas that could appear to work yet still be subtly broken.

Can you post a small sample of how you're allocating, using, and releasing your memory?

There are a couple of issues here.

1) You aren't casting the results of malloc() and realloc() to the appropriate type. They return a void* and that should be cast as needed.

2) You don't test the results of the calls for NULL which would indicate an error, such as an out-of-memory condition.

You aren't casting the results of malloc() and realloc() to the appropriate type. They return a void* and that should be cast as needed.

The cast is unnecessary in C, and including it (on top of being a potential maintenance issue) will hide the legitimate error of failing to include stdlib.h. One of the benefits of how C handles conversions to and from void* is you can do this to not even mention the type except in the pointer declaration:

p = malloc(sizeof *p); // Yay, no mention of p's type needed

The bigger issue in the ninja-edited code is using create as both the first argument and return of realloc. If realloc fails and returns NULL, you've lost your only reference to the memory. A temporary pointer is recommended. Some variation of this, for example:

T *temp = realloc(p, new_size);

if (temp != NULL) {
    p = temp;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.