1

I'm fighting with memory managment right now. It's verry funny for me :)

Here is simple app which I wrote. I can allocate memory in two ways.

int main (int argc,  const char * argv[])
{
    int *x;
    int *z;

    x = malloc(sizeof(int));
    z = (int *)sizeof(int);

    free(x);
    free(z);
}

Is there any difference between the ways of memory allocating used in the code above ?

jingo
  • 1,084
  • 5
  • 14
  • 23

6 Answers6

10

The second line doesn't allocate any memory, it's the equivalent of

z=(int *)4;

ie, z will point to the (unallocated and most likely non-existant) (virtual) memory at address 4. If you do something like:

*z=0;

your program will crash to an access violation.

Blindy
  • 65,249
  • 10
  • 91
  • 131
2

Is there any difference between the ways of memory allocating used in the code above?

The first one allocates memory. The second one does not.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
1

Yes. z = (int *)sizeof(int); isn't actually allocating memory. I believe the behavior is technically undefined, but since you are basically assigning z to some unknown portion of the heap. The corresponding call to free(z) could cause major issues if this is used in production code.

Of course, you do not have a corresponding call to free(z). You are freeing y. Since I don't know what y is, then I can't tell you what that will do.

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
0

The 2 statements should be combined .

The first allocates dynamic memory from the heap and returns a void pointer to that area. The second just makes a cast without allocating any memory.

The recommended way is :

int* a = (int *) malloc( sizeof(int ) );

Also you can use calloc which is the same as malloc, but it also initialize the allocated memory to 0 .

coredump
  • 3,017
  • 6
  • 35
  • 53
0

You actually want to cast the malloc statement into an int pointer. So

x = (int *) malloc(sizeof(int))

tekknolagi
  • 10,663
  • 24
  • 75
  • 119
  • `void*` is implicitly convertible to `int*`, so there is no need for a cast. – sth Oct 05 '11 at 14:14
  • 1
    hmm... just the way i was taught – tekknolagi Oct 05 '11 at 14:17
  • *Very* old implementations of C (before C89) had `malloc` return a `char *`, so a cast was necessary. This hasn't been true since the C89 standard was adopted, however. – John Bode Oct 05 '11 at 14:23
  • I don't think this answer deserves a negative vote. I'm upvoting it to the nonnegative integer 0. – a06e Jul 09 '12 at 23:32
0

You are not allocating memory for z, will cause segmentation fault if used.
If you are question is if or not you should typecast result of malloc it is better you don't. Please refer Do I cast the result of malloc? for more details.
Also a NULL check of the return value ofmalloc will do more good than bad!
Hope this helps!

Community
  • 1
  • 1
another.anon.coward
  • 11,087
  • 1
  • 32
  • 38
  • I disagree, what will a `NULL` check on the return value do for you? Let you write more code to just exit the program anyway? It won't even return `NULL` on Linux in out of memory conditions. – Blindy Oct 05 '11 at 14:23
  • I've used implementations where a memory allocation actually can fail by returning a null pointer - if you only ever write programs for Linux, and if you can ensure that over-commit will always be enabled (it's user-configurable), and you never allocate anything so big that it fails without trying, maybe then you can ignore the return value of `malloc`. But that's tying your code tightly to a particular environment and is terrible advice for general C programming. – Steve Jessop Oct 05 '11 at 14:29
  • @Blindy: Well Sir I have the tendency to do a `NULL` check before the operating on the return value of `malloc`. It is not always exit code from the program (from whatever little experience I have had). Well in the case of the question posted, you are right! – another.anon.coward Oct 05 '11 at 14:30
  • @Steve Jessop : I am little confused, because I have programmed throughout in Linux . Do you think that suggesting `NULL` check is a bad idea? I will be more than happy to correct my response! – another.anon.coward Oct 05 '11 at 14:32
  • @Steve, I actually never program in Linux. However in my opinion when you're so out of resources that your allocations are failing you can't really truly recover anyway, might as well let the whole thing crash. When does that ever happen anyway outside of development builds memory leaks :) – Blindy Oct 05 '11 at 14:34
  • @Blindy: Just seeking your opinion... Don't you think it might be possible that a sub-module of a fairly large module can have `malloc` failure and application can gracefully exit than crash? Please note I have no experience in non-Linux environment. It will be helpful to me to know your experience regarding this – another.anon.coward Oct 05 '11 at 14:39
  • @Blindy: that's not my experience. Perhaps I've worked on better-written OSes than you have, or anyway OSes designed to deal properly with resource constraints. The trouble with just shutting down on failure, or even worse carrying on with UB in the hope of a crash in the near future, is that it prevents the app from doing any clean shutdown. Just because you can't allocate 10MB for some library operation doesn't necessarily mean that your caller can't save the user's data before exit. – Steve Jessop Oct 05 '11 at 14:42
  • I'm having trouble imagining a well written, streaming application running out of memory. Just don't load the entire database file in memory to find a specific row in it... To answer your specific question, no, I honestly think checking for out-of-memory conditions is as productive as building windows to explain the user a stack overflow as occurred. – Blindy Oct 05 '11 at 14:43
  • @Steve, my point is more about how unlikely that is to ever happen. Granted most of my apps were either hosted on a web server with plenty of memory or on intranet computers (so they're guaranteed to be decent enough), but I just don't think it's worth the effort to check for these kinds of failure. – Blindy Oct 05 '11 at 14:45
  • @Blindy: Well Sir streaming applications are not the only kind of applications written! :) ... I guess in your experience you find such a check useless, but I have the tendency (and been advised to) do such check for a more graceful exit than a crash. Thank you for sharing you experience :) – another.anon.coward Oct 05 '11 at 14:53
  • In my whole career spanning 25 years I've never seen a definite case of a malloc call return NULL. I have seen programs bring systems to their knees by allocating vast quantities of memory and thus have to be killed. – JeremyP Jul 31 '12 at 10:37
  • @JeremyP: Right on sir! Even I have not seen it as such unless it was under stress testing of the system. Although most of the work I have dealt with has been on mobile devices, I have not seen a definitive case as such. Maybe this check can be added only on facing memory corruption or exhaustion under debugging environment. I have been wondering if this post should be deleted if it is too misleading - your suggestions regarding deletion of this post or any improvement are most welcome – another.anon.coward Aug 03 '12 at 17:14