Question

In the codes below, I can change the parameter of malloc to whatever values (at least the ones I have tried), and everything looks okay.

For example, I can change "3 * sizeof(float)" to "3 * sizeof(char)", or even zero. And I can still get the "correct" results. The heap size doesn't seem to matter at all.

This really confuses me. How can this happen?

The codes are written and run in Xcode 5.

float *favorites = malloc(3 * sizeof(float));

favorites[0] = 3.14158;
favorites[1] = 2.71828;
favorites[2] = 1.41421;

for (int i = 0; i < 3; i++) {
    printf("%.4f is favorite %d\n", favorites[i], i);
}

free(favorites);
favorites = NULL;
Was it helpful?

Solution

This is because by doing so your program invokes undefined behavior. Once UB invoked, all bets are off. You may get either expected or unexpected result.

Now try to do it without allocating memory to favoritee

float *favorites ;
...

and see what happen?

OTHER TIPS

Your program only looks like it works. In fact malloc internally allocates a big chunk of memory (at least one memory page) and returns pointer inside this memory area.

So, your pointer points somewhere to the beginning of memory page and nothing happens if you cross the border a little bit. If you pass the border too much (more than 4KB or 4MB) you will get an error.

Also if you call two mallocs and then pass over the range of the first allocated space, you will have problems, because malloc stores some of its internal data before returned pointer.

Anyway, from the language point of view, you have invoked an "undefined behaviour" which means nobody cares what happens if you do this. The behaviour of your program may change from one compiler version to another, from one system to another ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top