Thread: [C] malloc and fgets

  1. #1
    Registered User
    Join Date
    Nov 2010

    [C] malloc and fgets

    #include <stdlib.h>
    #include <string.h>
    #include <stdio.h>
    void memoryAlloc (int a);
    int main(int argc, char* argv[])
    	int choice;
    	fputs("Please enter the maximum length of string: ",stdout);
    	return 0;
    void memoryAlloc (int a){
    	char* arr;
    	arr = (char*)malloc( a * sizeof(char));
    	if (arr == NULL){
    		fputs("Failed to allocate memory!!!",stdout);
    	fputs("Please enter strings: ",stdout);
    	fgets(arr,sizeof(arr),stdin); // scanf("%s",arr);
    	printf("Entered strings: %s\n",arr);
    Hello, Ive started studying C for fun, and got a problem studying dynamic memry allocation part.
    I wrote this code to understand how to use malloc.
    I wanted to get a string from a user and then print a result.
    I really don't understand why my code doesnt allow to type strings.
    If I use scanf() instead of fgets, it works fine. Anyone got an idea why it happens??!!
    Last edited by baraq; 11-04-2010 at 09:15 PM. Reason: clearfying my question

  2. #2
    Registered User
    Join Date
    May 2010
    Last edited by Bayint Naung; 11-04-2010 at 09:24 PM.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    The other problem you have is mixing scanf() with fgets()

    > scanf("%d",&choice);
    This leaves trailing characters (specifically a newline) on the input stream

    > fgets(arr,sizeof(arr),stdin);
    This reads the remainder of the stream, up to the first newline. Typically, this is the only character.

    In response to your first prompt, try typing in something like

    > printf("Entered strings: %s\n",arr);
    This would print the !?
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fgets, fputs, and malloc.
    By eXeCuTeR in forum C Programming
    Replies: 41
    Last Post: 11-30-2007, 07:09 AM
  2. Reset fgets to read from the beginning of a file?
    By bivhitscar in forum C Programming
    Replies: 2
    Last Post: 05-20-2006, 11:42 PM
  3. print problem while using fgets()
    By learninC in forum C Programming
    Replies: 12
    Last Post: 05-15-2005, 09:29 PM
  4. malloc
    By powerboy in forum C Programming
    Replies: 11
    Last Post: 05-25-2003, 09:26 AM
  5. SSCANF help
    By mattz in forum C Programming
    Replies: 7
    Last Post: 12-10-2001, 04:53 PM