Trouble understanding Malloc, Calloc, and Realloc

This is a discussion on Trouble understanding Malloc, Calloc, and Realloc within the C Programming forums, part of the General Programming Boards category; Does this successfully allocate dynamic memory for the array? Also, what is the significance of '*' specifically when dealing with ...

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    244

    Trouble understanding Malloc, Calloc, and Realloc

    Does this successfully allocate dynamic memory for the array?

    Also, what is the significance of '*' specifically when dealing with malloc/calloc??

    In the code below I use-> '*' twice:

    1)in the declaration of the array with unknown number of slots
    2)while allocating dynamic memory....

    I know that * usually is a pointer of some sort...


    Thanks in Advance!

    Code:
    //Malloc exmaple
    #include <stdio>
    #include <stdlib>
    
    int main (void){
       
       int *studentAgeArray;
       int numStudents;
    
    
       printf("Please enter the number of students.\nEntry: \n");
       scanf("%d", &numStudents);
    
       num=(int*)malloc(sizeof(numStudents));
       
       
    
    system("PAUSE");
    return 0;
    }
    Last edited by matthayzon89; 10-17-2010 at 03:04 PM.
    Linklists use recursion to store what? ..... floats!

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,159
    That's a pretty messed up program, but to address your question: No. What is 'num' even? It's not a variable that I see declared. I think what you're shooting for is:
    Code:
    studentAgeArray = malloc(sizeof(*studentAgeArray) * numStudents);
    Also, double check your use of scanf(). That '%' sign in the second argument should be something else...
    If you understand what you're doing, you're not learning anything.

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    107
    Nope.

    This however, would:
    Code:
    //Malloc exmaple
    #include <stdio.h>
    #include <stdlib.h>
    
    int main (void){
       
       int *studentAgeArray;
       int numStudents;
    
    
       printf("Please enter the number of students.\nEntry: \n");
       scanf("%d", &numStudents);
    
    	// malloc wants us to tell it how many bytes we want.
    	// an int is sizeof(int) bytes, and we want numStudents
    	// integers, so we want sizeof(int) * numStudents bytes
    	// in total.
    	//
    	// In general, the idea is (myType*)malloc(sizeof(myType)*number_of_elements_I_want);
    
       studentAgeArray=(int*)malloc(sizeof(int) * numStudents); // Actually, malloc() could fail and return 0
    
    	// There are ways to correct this. I have never actually seen malloc fail, but whatever:
    	// studentAgeArray=0;
    	// while(studentAgeArray == 0) studentAgeArray=(int*)malloc(sizeof(int) * numStudents);
    	//
    	// This would either hang in an infinite loop if we can't get memory, or it would eventually
    	// allocate our memory
    
    	// This proves we allocated memory. Feel free to omit. It was just for the example.
       printf("studentAgeArray = %p\n", studentAgeArray);
    
    	// We have to free this dynamically allocated memory at some point
    	free(studentAgeArray);
       
    
    system("PAUSE");
    return 0;
    }
    A sample output is:
    Code:
    Please enter the number of students.
    Entry: 
    4
    studentAgeArray = 0x1244010

  4. #4
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,413
    Nope. malloc returns NULL if it fails, not 0.
    Furthermore, malloc in a loop like is a bad idea. Is your program going to sit there hogging up 100/50/33/25% CPU while malloc fails for an unknown reason?

    Quote Originally Posted by matthayzon89 View Post
    I know that * usually is a pointer of some sort...
    Then I think you need to actually learn what pointers are first.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Also, no need to cast malloc. In fact, this is not optional, DON'T CAST IT unless you are using a C++ compiler.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  6. #6
    Registered User
    Join Date
    Feb 2010
    Posts
    244
    Quote Originally Posted by Elysia View Post

    Then I think you need to actually learn what pointers are first.
    Pointer= An Address

    Maybe, you can answer the question and be helpful... instead of getting smart.
    Last edited by matthayzon89; 10-17-2010 at 03:09 PM.
    Linklists use recursion to store what? ..... floats!

  7. #7
    Registered User
    Join Date
    Feb 2010
    Posts
    244
    Thanks for all the responses!!! Especially @ QuadtraticFighte and claudiu!!!


    Very helpful....


    QuadtraticFighte, can you help me understand what the general format of calloc is and when would you use malloc instead of calloc?


    Also, in the example you gave above, how come everything need to equal studentAgeArray? is it because thats what we are allocating dynamic memory for?

    studentAgeArray=(int*)malloc(sizeof(int) * numStudents);
    Last edited by matthayzon89; 10-17-2010 at 03:12 PM.
    Linklists use recursion to store what? ..... floats!

  8. #8
    Registered User
    Join Date
    Oct 2010
    Posts
    107
    Quote Originally Posted by Elysia View Post
    Nope. malloc returns NULL if it fails, not 0.
    Furthermore, malloc in a loop like is a bad idea.
    Oh right, I forgot they are not interchangeable. Is it a difference between 64- and 32-bit systems?

    Quote Originally Posted by Elysia View Post
    Is your program going to sit there hogging up 100/50/33/25% CPU while malloc fails for an unknown reason?
    Yes, because I write crappy programs. HR directors take note. Kidding aside, we could probably just crash. I agree that would be better.

    Quote Originally Posted by matthayzon89 View Post
    Pointer= An Address
    That may or may not contain memory we have been allocated.

    Quote Originally Posted by matthayzon89 View Post
    QuadtraticFighte, can you help me understand what the general format of calloc is and when would you use one as opposed to the other?
    Well, calloc is called slightly differently. To compare malloc and calloc, it's

    Code:
    int* myArray = malloc(sizeof(int)*num_elements_I_want);
    int* myArray = calloc(num_elements_I_want, sizeof(int));
    With the malloc call, we just get the memory. It's values are uninitalized. With calloc, values are initialized to zero.
    Last edited by QuadraticFighte; 10-17-2010 at 03:12 PM.

  9. #9
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,413
    Quote Originally Posted by matthayzon89 View Post
    Pointer= An Address

    Maybe, you can answer the question and be helpful... instead of getting smart.
    I said that because I wanted you to read up on the concept of pointers, how they're used and why they're useful, because it seems you do not properly understand that.
    And if you don't understand pointers, then you won't understand dynamic memory allocation.

    Quote Originally Posted by QuadraticFighte View Post
    Oh right, I forgot they are not interchangeable. Is it a difference between 64- and 32-bit systems?
    All I can say is that NULL is preferable with pointers. I don't know what the exact requirements on the definition of NULL is.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    You can use either NULL or 0.
    Null Pointers

  11. #11
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,413
    Yes, but again, NULL signifies a NULL pointer; 0 does not, because it is an integer. Therefore, it is better to say malloc returns NULL on failure rather than 0.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User
    Join Date
    Feb 2010
    Posts
    244
    @ Elysia, thats understandable, thanks for clarifying.

    I am actually starting to get the hang of malloc (for arrays at least)

    what if you had an array of structs... can someone please give me a idea how to malloc that?

    Lets say the struct is declared as follows:

    Code:
    struct student{
    int num;
    int grade;
    int age;
    char name[20];
    };
    Lets say in main my struct variable declaration is:

    struct student* info;

    Suppose, I ask the user to enter a value for numStudents and they enter 20;

    So, does this allocate dyn. memory for an array (called info) of structs (of type student), of size numStudents, correctly?

    Code:
    info=(student*)malloc((student) * sizeof(numStudents));
    Last edited by matthayzon89; 10-18-2010 at 09:37 AM.
    Linklists use recursion to store what? ..... floats!

  13. #13
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    You would want something more like...
    Code:
    info = malloc(sizeof(student) * numStudents);
    That is the size of each element times the number of elements.

    This is where calloc can be very handy...
    Code:
    info = calloc(numStudents,sizeof(student));
    This sets up your array and initializes it to all zeros.

    There's no need to typecast the return of malloc, it's just a pointer.
    Last edited by CommonTater; 10-18-2010 at 09:55 AM.

  14. #14
    Registered User
    Join Date
    Feb 2010
    Posts
    244
    so, calloc usually comes in handy when I want to allocate memeory for an array of structs and initialize all the elements to zero at the same time, basically???



    thanks
    Linklists use recursion to store what? ..... floats!

  15. #15
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,413
    Yes.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc, realloc, calloc
    By newbie30 in forum C Programming
    Replies: 25
    Last Post: 08-13-2009, 01:14 PM
  2. Difference BW malloc() and calloc() and realloc()
    By svelmca in forum C Programming
    Replies: 2
    Last Post: 03-31-2009, 05:59 AM
  3. malloc and realloc
    By jayfriend in forum C Programming
    Replies: 4
    Last Post: 01-05-2007, 01:25 PM
  4. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 04:45 PM
  5. Linked list versus malloc and realloc.
    By Bajanine in forum C Programming
    Replies: 2
    Last Post: 06-20-2005, 08:08 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21