Thread: confused with memory allocation

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    184

    confused with memory allocation

    hello guys,

    i wirting a program to read a string using s fgets function. look in to the code what i havw written.

    Code:
    #include<stdio.h>
    #include<string.h>
    
    int main()
    {
            char *p;
            p=(char *)malloc(sizeof(char)*10);
            
            fgets(p,sizeof(p),stdin);
            fputs(p,stdout);
          
           getchar();
    }
    when i run this program i allocated only 3 bits int the memory rather than allocating 10 bytes. and here is the sample output of what it does

    Code:
    hello world
    hel
    i don't understand why it is can any one can explain what it is please

    thax very much in advance

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    >when i run this program i allocated only 3 bits int the memory rather than allocating 10 bytes.

    No. You told fgets to stop when it reaches one less than the size of the pointer rather that the amount of data it points to.
    Code:
    fgets(p,sizeof(p),stdin);
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
       size_t size = 20;
       char *p = malloc(size);
       fgets(p, size, stdin);
       fputs(p, stdout);
       getchar();
       return 0;
    }
    /* my output
    hello world
    hello world
    */
    Last edited by Dave_Sinkula; 02-26-2005 at 10:10 PM. Reason: Added code.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    184
    thax very much it works fine for me now

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C memory allocation to c++
    By markucd in forum C++ Programming
    Replies: 2
    Last Post: 11-30-2005, 05:56 AM
  2. Understanding Memory Allocation
    By Ragsdale85 in forum C Programming
    Replies: 7
    Last Post: 10-31-2005, 08:36 AM
  3. memory allocation ptr to array? how?
    By kokopo2 in forum C Programming
    Replies: 8
    Last Post: 09-01-2005, 05:06 PM
  4. Memory allocation and deallocation
    By Micko in forum C++ Programming
    Replies: 3
    Last Post: 08-19-2005, 06:45 PM
  5. Problems with memory allocation in classes
    By MathFan in forum C++ Programming
    Replies: 6
    Last Post: 01-09-2005, 02:05 AM