Thread: How would you optimize this code? (Memory allocation for character input)

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    101

    How would you optimize this code? (Memory allocation for character input)

    This is maybe the last exercise I will do of my course (yet finished). We have 6 exercises that our instructor left in the last class, 6 exercises about memory allocation, this is the fourth one.

    Statement: Insert characters through keyboard one by one; the program must ask Y/N choice to continue inserting characters (one by one). Use realloc function for memory allocation. The program must print all the characters inserted.

    I have been working in the program. I am not lazy at least, you know. I tried to solve it and I'm happy, I solved it. The code works "like a charm" but I want to use the correct code according to your recommendations. Please, don't blame me too much, I promise you I am making the effort to go to the right way, but still I need more practice. I am using some code thanks to laserlight. I know there is room for improvements, that's the reason I'm posting the code here. Compiled in C Now, the code:

    Code:
    #include <stdio.h>#include <stdlib.h>
    #include <string.h>
    #define MAX_SIZE 10//No magic numbers, I take your advice seriously men.
    
    
    int main()
    {
        int cont=0;
        char *ptr;//Pointer to store characters
        char c;
        char choice;//Character to read (Y/N)
    
    
        ptr=calloc(MAX_SIZE, sizeof(char));//Allocate at least 10 characters
    
    
        if (!ptr) {//Laserlight code, finally understood EXIT_FAILURE
            fprintf(stderr, "There is not enough memory.\n");
            return EXIT_FAILURE;
        }
    
    
        do {//do while loop to work the loop at least once
            printf("Insert a character: ");
            scanf(" %c", &c);//I accept more efficient alternatives
            ptr=realloc(ptr, MAX_SIZE * sizeof(*ptr));//re-allocate (resize) memory for character read to be stored
    
            if (!ptr) {//Laserlight code again for re-allocating
                fprintf(stderr, "La realocacion ha fallado por falta de memoria.\n");
                return EXIT_FAILURE;
            }
            printf("Insert more characters: (Y/N)");//To insert character one by one
            scanf(" %c", &choice);
            ptr[cont++]=c;//Advance in the loop
        } while (choice=='Y' || choice=='y');//While user press Y but also consider y, I took case sensitive in consideration
    
    
        ptr[strcspn(ptr, "\n")] = '\0';//Laserlight code
        printf("The characters inserted are: %s\n", ptr);
        free(ptr);//Free memory at the end of the program
    
    
        return 0;
    }
    Anny advice to make it better would be greatly appreciated. Only in C, not C++, I compiled in C and I'm working in C and I'm in C forum. Now I'm thinking, free is correctly placed? should I put another free above after calloc?

    I feel like the Cristiano Ronaldo of programming . No, no, that was a joke to calm the environment.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Your realloc isn't making the memory any bigger, because you're not changing the size.

    Code:
    size_t used = 0;  // how much you've used
    size_t maxAvailable = 0 ; // how much is actually available
    char *ptr = NULL; // where we're storing the data
    // setting ptr to NULL means we don't have to have an initial malloc
    
    // .. your loop
    
    // Every time you want to add something to ptr, do this
    if ( used == maxAvailable ) {
      // the new size is 16 the first time around, or double what it was last time
      // something like newMax = maxAvailable+1 would cause thrashing - don't do it
      size_t newMax = maxAvailable == 0 ? 16 : (maxAvailable * 2);
    
      // cannot use ptr yet, realloc might fail - but ptr would still be valid
      void *temp = realloc( ptr, newMax * sizeof(*ptr) );
      if ( temp ) {
        // success!
        ptr = temp;
        maxAvailable = newMax;
      } else {
        // failure
        // print error message
        // do something with ptr
        // do NOT go onto do ptr[used++] below
      }
    }
    
    // now update memory
    ptr[used++] = c;

    > while (choice=='Y' || choice=='y');
    Where do you input choice?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2017
    Posts
    101
    Excuse me for double post. I thought it failed after submitting.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Optimize memory management
    By merafiq in forum C Programming
    Replies: 8
    Last Post: 10-06-2015, 09:42 AM
  2. Help me to optimize this code
    By Fn00 in forum C Programming
    Replies: 12
    Last Post: 09-27-2015, 04:28 PM
  3. How can i optimize this code
    By ArunS in forum C Programming
    Replies: 15
    Last Post: 08-08-2011, 02:11 PM
  4. Please help me optimize my code
    By lazyme in forum C++ Programming
    Replies: 3
    Last Post: 01-25-2010, 04:05 AM
  5. character input using fgetc() code???
    By lesrhac03 in forum C Programming
    Replies: 3
    Last Post: 03-27-2008, 10:55 PM

Tags for this Thread