Difference between two memory allocation example?

85 views Asked by At

In my understanding,

Example1

cPtr = (char*)malloc(100);

Example2

1 char c = 0;
2 char* cPtr = &c
3 cPtr = (char*)malloc(100);

In Example1, malloc creates an memory space and returns the the first block of address of allocated memory. So cPtr gets an arbitrary address inside heap.

In Line 2 of Example2, cPtr is pointing to c. So cPtr has an address of c.

At this moment, when you execute line3 of Example 2, What would be the value of cPtr? Does it get an arbitrary memory address as I mentioned in Example1? Or, Does it keep the address of c and creates a spaces?

3

There are 3 answers

5
Carl Norum On BEST ANSWER

Does it get an arbitrary memory address as I mentioned in Example1?

Yes. That line just overwrites the previous value of cPtr.

Or, Does it keep the address of c and creates a spaces?

No, it doesn't "keep" anything. cPtr is overwritten with the return value of the malloc() call, which points to some block of memory, just the same as your first example.

Lines 1 and 2 of your second example are no-ops, essentially.

0
zubergu On

malloc returns value that succesfully can initialize or change value of pointer.
Initialization takes place in Example1, changing value of cPtr takes place in Example2.
That's the only difference between those two.

3
AnT stands with Russia On

With regard to the value of cPtr, in your second example line 3 completely discards all effects of line 1 and 2. I.e. the value returned by malloc simply overwrites the previous value in cPtr. So, in the second example lines 1 and 2 make absolutely no impact on the code behavior.

In other words, both examples are 100% equivalent, with the second one having two extra lines of completely inconsequential ("dead") code.