Thread: malloc () test

  1. #1
    Unregistered
    Guest

    Question malloc () test

    I am new to c

    how can I test that malloc() has successfully giving 26 bytes of memory

    example t=(char*)malloc(26 * sizeof(char));

    how can i test this function

    thanks

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    If malloc fails then it will return a NULL pointer, otherwise you got your memory:
    Code:
    var = malloc ( 26 * sizeof ( char ) );
    if ( var != NULL ) {
      /* It's good, work with it. */
    }
    else {
      /* Bad, handle the error */
    }
    And please don't cast malloc, it's not needed and can hide other problems.

    -Prelude
    My best code is written with the delete key.

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    You make sure that it's return value is not NULL. If it is, it failed.
    Code:
    if ((ptr = malloc(26)) == NULL)
    {
    	printf("memory problem!");
    	return 1;
    }
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  4. #4
    Unregistered
    Guest

    Thumbs up

    Thank you all for the help

    But is there a way to print how much memory was assigned?

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >But is there a way to print how much memory was assigned?
    You can't be sure exactly how much malloc gave you since it can and often does give you slightly more than you ask for and sizeof won't work with dynamic memory. So maintain a size variable which holds the size you gave malloc and use that.

    -Prelude
    My best code is written with the delete key.

  6. #6
    Unregistered
    Guest
    thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Speed test result
    By audinue in forum C Programming
    Replies: 4
    Last Post: 07-07-2008, 05:18 AM
  2. the basics of malloc
    By nakedBallerina in forum C Programming
    Replies: 21
    Last Post: 05-20-2008, 02:32 AM
  3. Integer Emulation
    By Elysia in forum C++ Programming
    Replies: 31
    Last Post: 03-18-2008, 01:03 PM
  4. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM