pointers and malloc()

i have this program that allocs memory from the stak. it doesnt work tho.
here is my code
1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
        int *mem_handle = ((int*)malloc(sizeof(mem_handle));
        if(mem_handle = NULL )
        {
                return 1;
          }

        *mem_handle = 7;
        free(mem_handle);
        mem_handle = NULL;
        return 1;
}

how can i fix this?
Take sizeof(int) instead. As it is, you are allocating enough space for an int* instead of an int.
Have you tried using "new"? This should work just fine for what I think you're trying to do: http://www.cplusplus.com/doc/tutorial/dynamic/

if(mem_handle = NULL )

This is an error. = is the assignment operator. For comparisons, use ==.
Last edited on
thanks for the replies! im trying to lern c like framework! so i have to change sizeof(mem_handle) to sizeof(int)?
Oh.

...

Yes, that would be a problem.
iv changed the code and now it works! next up file io!

thanks!
+1 to using new.

malloc should be avoided in C++.

A better way to do the above:

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
        int *mem_handle = new int;
//        if(mem_handle = NULL )  // no need for any of this, new will throw
//        {                          an exception if it fails, so you don't have to 
//                return 1;          check for error return
//          }

        *mem_handle = 7;
        delete mem_handle;
        mem_handle = NULL;
        return 1;
}
didnt you read what i said? its c not c++!
Why learn C? If you learn C++, you know C.

And malloc allocates memory on the heap, not the stack. :)
Well, the philosophies for the two languages are quite different and some C features have been deprecated in favor of some C++ features, meaning they don't get much book-space. :/

-Albatross
Why learn C? If you learn C++, you know C.

Not really. The C like approach is very different from a clean C++ approach. Though it's probably easier to get started with C++ and move on to C than the other way round, especially if you are a newbie programmer.
Well, the philosophies for the two languages are quite different

Very much agreed. C has its own idioms, too.
didnt you read what i said?


You didn't mention that in your original post. But I see now you mentioned it in a follow up post. So I guess I overlooked that.

But you know what? Blow me. If you're going to snap at me for trying to help then I won't try to help any more.
@Disch and anyone planning to post in this thread:
http://cplusplus.com/forum/lounge/38341/3/#msg206304

-Albatross
Topic archived. No new replies allowed.