Thread: Malloc,calloc..Sscanf.

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    151

    Malloc,calloc..Sscanf.

    Hello ,

    I will have two questions . First I havent got a enough information about the funcitons : malloc,calloc,realloc. Can anyone show me a direction to a source or can anyone directly explain their jobs detailed?
    Secondly , does the vary the sscanf function returns depends on the how many variable it used? By variable I mean the variables that we save the varies that we took from the string we put into the first argument of sscanf function.

    I hope I made my questions clear. I will be glad if you help. Thank you..

    (for example sscanf(s,"%d",&a)==1 ??? )

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    Yes for sscanf(), RTFM.

    Consider using a manual, eg http://www.opengroup.org/onlinepubs/...ns/malloc.html

  3. #3
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Real brief (and from memory, so check what I'm saying yourself):

    • malloc()

      Allocates contiguous memory in terms of bytes. Accepts a size_t as an argument and returns a void *. If the memory could not be allocated, the return value is NULL.
    • calloc()

      Similar to malloc(), with a few small changes. It accepts two args, one being the size of one element, and the other being the amount of elements. Another difference is that calloc() initializes all bytes of the memory it allocates to 0. As with malloc(), if the memory could not be allocated, NULL is returned.
    • realloc()

      This function is used to change the size of a block of memory allocated by either malloc(), calloc(), or realloc(). You pass it the pointer to the original block of memory, and specify the new size. If it is able to perform the memory resize, it returns a pointer to the new block of memory. If it couldn't resize the old block, it'll try to make a new block and copy all of the data from the old block to the new block. It then frees the old block. If the pointer you give it to resize is NULL, it behaves similar to malloc(). If it couldn't manage to resize the block of memory, or create a new block upon receiving a NULL pointer, it returns NULL.


    As far as sscanf() and the scanf() family of functions, yes, the return value is the number of variables that received valid values. If this return value is not equal to the number of variables you gave it, something went wrong with the assignment of at least one variable (or something major went wrong).

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Try http://www.hmug.org/man/3/malloc.php

    Yes, sscanf(s, "%d", &i) would return 0 if s doesn't contain a number, 1 if there is a number in s. Note also that i will only be filled in if it returns one.

    sscanf(s, "%d %d %d", &i, &j, &k) could return any number between 0 and 3, depending on what's in s.

    --
    Mats

  5. #5
    Day Dreamer
    Join Date
    Apr 2007
    Posts
    45

    not really

    I think your hopes didn't come out true.
    The question is kinda not clear to me.

    for the 1st question refer the man pages, if you dont know what they are then search Google may be the search query "malloc man page" and see the links, you'll get all you need.

  6. #6
    Registered User
    Join Date
    Jul 2007
    Posts
    151
    Yea zombie I did that before , then I got the teorical base , I just wanted to know if there are more about them...Thank you all , you clarified all my questions..

  7. #7
    Registered User
    Join Date
    Jul 2007
    Posts
    151
    So , I wonder if I do this :

    >char *array=malloc(10*sizeof(char));
    >printf("%d",sizeof(array));

    output is 10?? Or I didnt get anything right?

  8. #8
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    Depending on your computer, the output would most probably be 4.

    You're asking for the sizeof the pointer, not what it points to.

  9. #9
    Day Dreamer
    Join Date
    Apr 2007
    Posts
    45
    yes it should give you 4 as array is the pointer and the sizeof operator when applied on a pointer shall return you 4 on the machines we normally use today.

  10. #10
    Registered User
    Join Date
    Jul 2007
    Posts
    151
    I am sorry It should have been
    >printf("%d",sizeof(*array));

  11. #11
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    That will print 1 because a char is one byte.

  12. #12
    Registered User
    Join Date
    Jul 2007
    Posts
    151
    But I did array=malloc(10*sizeof(char)) before I printed the sizeof(*array) .. Dint I allocate a 10 char memory to array ? So shouldnt it print out 10??

    But Is it because When I do that I set a 10 lenght string and the array points to the first component of the string and that is 1 byte?

    Also I wonder :

    >char *array=malloc(10*sizeof(char));
    >gets(array);

    I deliberately use gets to lead program to an error. But I enter an input more than 10 character , it does not give error. What is the problem. I think I couldnt get what malloc does..
    Last edited by ozumsafa; 07-25-2007 at 04:04 AM.

  13. #13
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677

    Thumbs up

    Quote Originally Posted by ozumsafa View Post
    But I did array=malloc(10*sizeof(char)) before I printed the sizeof(*array) .. Dint I allocate a 10 char memory to array ? So shouldnt it print out 10??

    But Is it because When I do that I set a 10 lenght string and the array points to the first component of the string and that is 1 byte?

    Also I wonder :

    >char *array=malloc(10*sizeof(char));
    >gets(array);

    I deliberately use gets to lead program to an error. But I enter an input more than 10 character , it does not give error. What is the problem. I think I couldnt get what malloc does..
    Well, it will crash EVENTUALLY if you input a long enough string - unless of course the compiler generated some "memory protection code" or some such.

    The case here is that you don't really know what you're overwriting, and how far that is from anything "important" that will make the code crash. Imagine that malloc internally works like this:

    Code:
    void *malloc(size_t size) {
        if (list_of_blocks == NULL) {
            list_of_blocks = allocate_block(MEGABYTES * 4);
    
        block = split_block(list_of_blocks, size);
        return block;
    }
    Imagine also that your call to malloc is the first one (so list_of_blocks is NULL), we grab a 4MB block of memory, and split it into smaller blocks. So the next "bad memory address" is 4MB from where you got your memory...

    Under other circumstances, it may be much closer to the end.

    If you're using the keyboard to type into the gets, it may take quite some time to type megabytes of data... [keyboard repeat rate is something like 10 keys per second if you hold a key down. 4M / 10 = 400000s = 100+ hours...]

    Now of course, I just made that malloc function up - but I do know that malloc at least SOMETIMES allocates large chunks of memory and then splits it into smaller pieces, because that's one way to implement a malloc function - it is generally "expensive" to ask the operating system for memory, so you don't want to do that every time some user wants ten or a hundred bytes - particularly since most OS's don't support allocating small blocks of memory, only in multiples of 4K or some such. So to spread the cost of asking for memory from the OS, malloc "guesses" what the app needs, and then splits it to smaller chunks as needed.

    Each combination of OS and C-library will implement malloc slightly differently, but the general principle is similar in most cases.

    --
    Mats

  14. #14
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Quote Originally Posted by ozumsafa View Post
    But I did array=malloc(10*sizeof(char)) before I printed the sizeof(*array) .. Dint I allocate a 10 char memory to array ? So shouldnt it print out 10??
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    unsigned long foo( int (*p_stack)[5] )
    {
      return sizeof p_stack;
    }
    
    int main( void )
    {
      int p_auto[] = { 0, 1, 2, 3, 4, };
      int *p_heap = malloc( sizeof *p_heap * 5 );
      if ( p_heap )
      {
        printf( "sizeof p_auto = %lu\n", sizeof p_auto );
        printf( "sizeof p_auto[0] = %lu\n", sizeof p_auto[0] );
        printf( "sizeof p_auto / sizeof p_auto[0] = %lu ;)\n", sizeof p_auto / sizeof p_auto[0] );
        printf( "sizeof p_heap = %lu\n", sizeof p_heap );
        printf( "sizeof *p_heap = %lu\n", sizeof *p_heap );
        printf( "sizeof p_stack = %lu\n", foo( &p_auto ) );
    
        free( p_heap );
        p_heap = NULL;
      }
      return 0;
    }
    
    /**
    * sizeof p_auto = 20
    * sizeof p_auto[0] = 4
    * sizeof p_auto / sizeof p_auto[0] = 5 ;)
    * sizeof p_heap = 4
    * sizeof *p_heap = 4
    * sizeof p_stack = 4
    */
    Building on what the others had said, the size of some object really depends how it was allocated, and where in the code you decide to ask. sizeof is a special function provided by the compiler that computes the size of an object on a function's stack.

    And you will notice that pointers often occupy the stack in a function; ones like p_heap might be 4 or longer on other systems. The size of a pointer is the byte-width RAM requires to store a memory address. The size of an array on the other hand is much different. The array uses all the memory it needs from the function stack. Therefore we can conclude that the size of p_auto is accurate.

    So, what to learn from all of this: keep a variable handy that knows the length of a pointed to array, because it is hard to tell otherwise. If you need to know the size of a pointed to object (like int), dereference the pointer first.

  15. #15
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    gets does not check the buffer size...
    it starts from the first byte pointed by its argument and writes till the user input end...

    that's why you should not use it - use fgets as FAQ suggests
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sscanf and string handling question
    By ursula in forum C Programming
    Replies: 14
    Last Post: 05-30-2009, 02:21 AM
  2. Problems reading formatted input with sscanf
    By Nazgulled in forum C Programming
    Replies: 17
    Last Post: 05-10-2006, 12:46 AM
  3. sscanf question
    By Zarkhalar in forum C++ Programming
    Replies: 6
    Last Post: 08-03-2004, 07:52 PM
  4. Simple sscanf mystery
    By registering in forum C Programming
    Replies: 4
    Last Post: 06-10-2003, 11:47 PM
  5. sscanf (I think)
    By RyeDunn in forum C Programming
    Replies: 7
    Last Post: 07-31-2002, 08:46 AM