Thread: memory allocation

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    31

    Question memory allocation

    hi

    i am try to create a dynamic array of char

    this is what i have done

    Code:
    char *temp;
    
    unsigned int tempSize = 0;
    
    tempSize = 8212;
    
    temp = (char *) malloc(tempSize);
    
    printf("size of temp %d\n", sizeof(temp));

    what gets printed is

    size of temp 4

    shouldnt the size of temp be 8212?

  2. #2
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Nope. The pointer is still a pointer no matter how much memory you allocate to it. The only difference is, instead of pointing to nothing, it's pointing to 8212 bytes of memory. You can still access it like an array, the memory is there. Also you shouldn't, and in this case don't need to, cast malloc.
    Sent from my iPadŽ

  3. #3
    Registered User
    Join Date
    Feb 2006
    Posts
    31
    ok thanks =D

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    And you should also free() dynamically allocated memory.

    Also you shouldn't, and in this case don't need to, cast malloc.
    I can't think of too many cases that you would need to cast malloc(). Unless you've using Turbo C or something.

    sizeof(a pointer) will return 4 on 32 bit machines and 2 on 16 bit ones. It won't return the number of bytes allocated to that pointer, as you've found out. There is no way of knowing (that I'm aware of) how to figure out how much memory is allocated to a particular pointer. It's best just to keep the size for future reference.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

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