Thread: malloc problem

  1. #1
    Registered User
    Join Date
    Mar 2012
    Location
    Hong Kong
    Posts
    13

    Post malloc problem

    I dont know why the program doesn't allow to enter next line when the input is 1023 char...
    but 1022 char is working properly, i think the problem is in the malloc
    any comments?
    The purpose of the program is to read the inputted text form user, and printf in order to the screen.
    Code:
        while (1) {
            sarray[nostring] = (char*)malloc(sizeof(temp));
    
    
            fgets(temp, 1024, stdin);
            if (temp[0] == '\n')
                break;
    
    
            strcpy(sarray[nostring], temp);    
            numstring++;
        }
    
        free(strarray);
    
    
      getchar();    
    }
    Last edited by Oscar Wong; 05-27-2012 at 07:28 AM. Reason: question solved

  2. #2
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    That's how fgets works, from the fgets manual page.

    char *
    fgets(char *restrict s, int n, FILE *restrict stream);

    The fgets() function reads at most one less than the number of characters specified by n from the given stream and stores them in the string s.
    Edit: The reason for this is that a string is terminated by a '\0' character, if fgets read all 1024 characters then it would have to place the null character at index 1025, which would be out of bounds.
    Last edited by Subsonics; 05-27-2012 at 07:02 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc problem
    By RicOz6 in forum C Programming
    Replies: 5
    Last Post: 02-19-2011, 10:23 AM
  2. Problem in malloc
    By lolguy in forum C Programming
    Replies: 20
    Last Post: 01-06-2009, 07:33 PM
  3. malloc problem
    By aie0 in forum C Programming
    Replies: 4
    Last Post: 05-29-2007, 06:40 AM
  4. malloc() problem...
    By Junior89 in forum Windows Programming
    Replies: 4
    Last Post: 01-14-2006, 07:03 PM
  5. Problem with the malloc (?)
    By GaPe in forum C Programming
    Replies: 6
    Last Post: 05-11-2002, 11:07 AM