Thread: Heap Memory

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    224

    Question Heap Memory

    What is wrong with this code:

    Code:
    	integers = malloc(amount * sizeof(int));
    Where the integers and amount are initialised:

    Code:
    int *integers;
    int amount = 3;

  2. #2
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    If it's C++ you prolly have to cast malloc, but should use new anyway. malloc. new.

  3. #3
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    besides not free()'ing the memory, i cant see anything wrong with it. since you are asking what is wrong, you must be having a problem with it. so what is the problem? either that or this is a direct homework question.

  4. #4
    Registered User
    Join Date
    Nov 2006
    Posts
    224
    Quote Originally Posted by nadroj View Post
    besides not free()'ing the memory, i cant see anything wrong with it. since you are asking what is wrong, you must be having a problem with it. so what is the problem? either that or this is a direct homework question.
    Compiler error: cannot convert from void* to int*

  5. #5
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    Cast malloc then.

  6. #6
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    sorry, i was compiling it as C code, not C++. for C code using gcc and options "-Wall -pedantic -std=c99" gave no warning or errors. but twomers gave a hint to how to solve the error for C++.

  7. #7
    Registered User
    Join Date
    Nov 2006
    Posts
    224
    Thanks! twomers

  8. #8
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Whilst a cast will remove the compiler error, the right thing is to use "new", as suggested in post #2 by twomers.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems with shared memory shmdt() shmctl()
    By Jcarroll in forum C Programming
    Replies: 1
    Last Post: 03-17-2009, 10:48 PM
  2. Memory usage and memory leaks
    By vsanandan in forum C Programming
    Replies: 1
    Last Post: 05-03-2008, 05:45 AM
  3. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  4. Accessing Video Memory Information...need help
    By KneeLess in forum C++ Programming
    Replies: 8
    Last Post: 08-24-2003, 03:53 PM
  5. Memory handler
    By Dr. Bebop in forum C Programming
    Replies: 7
    Last Post: 09-15-2002, 04:14 PM