Thread: how to validate memory allocation

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    39

    how to validate memory allocation

    Anyone help me to validate memory allocation using malloc function for the following code

    Code:
     int i,j,*page[16],u=0,p;
     int *array1[4];                                                                                                                           
    
                                                                                                                                 
      for(i=0;i<=1;i++)                    
       {
         array1[i] = (int *)malloc(16*sizeof(int));
         printf("\npartition=%u\n",array1[i]);
       }
    thanks in advance

  2. #2
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    What do you mean "validate"? If you want to check whether an allocation succeeded, just check against NULL:
    Code:
    int *p;
    p = malloc(50 * sizeof *p); /* cast is not necessary */
    if(p == NULL) { /* oops, the allocation failed */ }
    Also, the correct conversion specifier for printing out a pointer is %p, not %u. And here a cast is required to be completely correct, as %p requires a void* (so it follows, of course, that void pointers themselves needn't be cast).
    Code:
    /* above code, then... */
    printf("%p\n", (void *)p);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory allocation question
    By dakarn in forum C Programming
    Replies: 11
    Last Post: 12-01-2008, 11:41 PM
  2. Dynamic memory allocation.
    By HAssan in forum C Programming
    Replies: 3
    Last Post: 09-07-2006, 05:04 PM
  3. Dynamic memory allocation...
    By dicorr in forum C Programming
    Replies: 1
    Last Post: 06-24-2006, 03:59 AM
  4. C memory allocation to c++
    By markucd in forum C++ Programming
    Replies: 2
    Last Post: 11-30-2005, 05:56 AM
  5. Understanding Memory Allocation
    By Ragsdale85 in forum C Programming
    Replies: 7
    Last Post: 10-31-2005, 08:36 AM