我在戴尔工作站上使用 gcc 和 Linux Ubuntu,在联想工作站上使用 Microsoft Visual C++,并得到了一些我想解释的以下差异。
一位同事甚至写了一个自己的 malloc,我想知道内存分配有哪些策略。似乎有不同的策略来分配内存中的位置。(g)cc、nmake 和其他之间似乎也有区别。例如,(g)cc 似乎忽略了已释放的旧分配,而是分配了新释放的资源。这是 Microsoft Visual C++ 的外观:
Message MA01 from malloc.c: Hello, memory-allocating World!
MA02: Main array successfully allocated, with size 48 bytes.
MA03: Main array malloc returned address 988360 (dec), f14c8 (hex).
MA04: Main array now contains the following string:
abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstu
g-count successfully allocated, with size 4 bytes.
g-count malloc returned address 988472 (dec), f1538 (hex).
Number of g's in array is 2.
Executed free( gcountp );
MA05: Cowabunga array successfully allocated, with size 11 bytes.
MA06: Cowabunga array malloc returned address 988472 (dec), f1538 (hex).
MA07: Cowabunga array now contains the following string: Cowabunga!
MA08: Main array now contains the following string:
Cowabunga!
g-count successfully allocated, with size 4 bytes.
g-count malloc returned address 988544 (dec), f1580 (hex).
Number of g's in array is 1.
Executed free( gcountp );
MA09: Executed free( arrayp );
g-count successfully allocated, with size 4 bytes.
g-count malloc returned address 988360 (dec), f14c8 (hex).
Number of g's in array is 1.
Executed free( gcountp );
MA10: Executed free( extrap );
在 Ubuntu(Dell) 上使用 gcc,它看起来像这样:
Message MA01 from malloc.c: Hello, memory-allocating World!
MA02: Main array successfully allocated, with size 48 bytes.
MA03: Main array malloc returned address 30273552 (dec), 1cdf010 (hex).
MA04: Main array now contains the following string:
abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstu
g-count successfully allocated, with size 4 bytes.
g-count malloc returned address 30273616 (dec), 1cdf050 (hex).
Number of g's in array is 2.
Executed free( gcountp );
MA05: Cowabunga array successfully allocated, with size 11 bytes.
MA06: Cowabunga array malloc returned address 30273616 (dec), 1cdf050 (hex).
MA07: Cowabunga array now contains the following string: Cowabunga!
MA08: Main array now contains the following string:
Cowabunga!
g-count successfully allocated, with size 4 bytes.
g-count malloc returned address 30273648 (dec), 1cdf070 (hex).
Number of g's in array is 1.
Executed free( gcountp );
MA09: Executed free( arrayp );
g-count successfully allocated, with size 4 bytes.
g-count malloc returned address 30273648 (dec), 1cdf070 (hex).
Number of g's in array is 1.
Executed free( gcountp );
MA10: Executed free( extrap );
简而言之:
使用 MSVC++:
alloc() got addr1
alloc() got addr2
alloc() got addr3
free(ALL)
alloc() got addr1
在 Ubuntu 上使用 gcc:
alloc() got addr1
alloc() got addr2
alloc() got addr3
free(ALL)
alloc() got addr3
如何解释这些差异?...