c# - Initialization of memory allocated with stackalloc - Stack ...
文章推薦指數: 80 %
From the spec: 18.8 Stack allocation. The content of the newly allocated memory is undefined.
Home
Public
Questions
Tags
Users
Companies
Collectives
ExploreCollectives
Teams
StackOverflowforTeams
–Startcollaboratingandsharingorganizationalknowledge.
CreateafreeTeam
WhyTeams?
Teams
CreatefreeTeam
CollectivesonStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
Learnmore
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
Learnmore
Initializationofmemoryallocatedwithstackalloc
AskQuestion
Asked
10years,3monthsago
Modified
5monthsago
Viewed
2ktimes
14
3
IfI'mallocatingmemorywithstackallocinC#,isthatmemoryinitialized(with0)?
Thedocumentationdoesn'tspeakofthatandonlytellsthatthecorrectamountisreserved.
Inmytestssuchmemorydefaultedto0,butthatdoesn'tmeanit'sguaranteedthough.
c#unsafestackalloc
Share
Improvethisquestion
Follow
askedDec30,2011at11:37
frumbaelafrumbaela
34111silverbadge88bronzebadges
Addacomment
|
2Answers
2
Sortedby:
Resettodefault
Highestscore(default)
Trending(recentvotescountmore)
Datemodified(newestfirst)
Datecreated(oldestfirst)
Helpusimproveouranswers.Aretheanswersbelowsortedinawaythatputsthebestansweratornearthetop?
Takeashortsurvey
I’mnotinterested
6
+200
Yes,thespecsaysitisundefined,butthecompileremitslocallocCILintructionforstackalloc.AndthisiswhatECMASpecssaysaboutlocalloc:
Thelocallocinstructionallocatessize(typenativeunsignedint)
bytesfromthelocaldynamicmemorypoolandreturnstheaddress(a
managedpointer,type&)ofthefirstallocatedbyte.Theblockof
memoryreturnedisinitializedto0onlyiftheinitializeflagonthe
methodistrue(seePartitionI).Theareaofmemoryisnewly
allocated.Whenthecurrentmethodreturnsthelocalmemorypoolis
availableforreuse.
Theinitializeflag,alsoknownaslocalsinitflag,isemittedforeverymethodbythecompilerbecauseitisrequiredforverifiablecode.
Pleaselookatthisissueoncoreclraskingtostopzeroingmemoryonstackalloc.Attheendoftheissuejkotassays:
Thecurrentplanis:
C#willkeepzeroinitializingbydefault.Changingthedefaultwould
betoobreaking.Wehaveasetofissuesopenedtomakethezero
initializationdonebytheJITmoreefficientorreduceneedforit
(#13827,#13823,#13825)Folkswhoreallywanttogetthelastbitof
performancebyavoidingzeroinitializationcanusecustomILLinker
step(mono/linker#159)whentheyknowwhattheyaredoing.Wedothis
forCoreLibtoday(viaVMhack,butweshouldswitchtotheILLinker),
andweplantoexperimentwiththisinCoreFX(dotnet/corefx#25956).
Basedontheresultsoftheseexperiments,wemayconsiderintroducing
amorestreamlinedwaytodothisinfuture.@ahsonkhanYoushould
considerexperimentingwithitinCoreFXLabaswellifyoubelieve
thatitwouldhelp.
Andseethiscsharplangproposal
Sotheconclusionis:thememoryisinitializedtozeroinpractice
Howeverthereisabug/featureinthecompilerthatpreventsfromemitinglocalsinitflag.Unsafemethodsthatdon'tdeclareothervariablesandusethestackallocatedvariableonlytopassingittoothermethod,don'tgetmarkedwiththelocalsinitflag.
Hereisanexampleofsuchbug/feature:
usingSystem;
usingSystem.Diagnostics;
usingSystem.Runtime.CompilerServices;
namespaceInformalTests
{
classProgram
{
constintn=100_000_000;
staticunsafevoidMain(string[]args)
{
varwatch=Stopwatch.StartNew();
for(inti=0;i
延伸文章資訊
- 1is allocated with - Linguee | 中英词典(更多其他语言)
大量翻译例句关于"is allocated with" – 英中词典以及8百万条中文译文例句搜索。
- 2ALLOCATE在劍橋英語詞典中的解釋及翻譯
State funds will not be allocated to the program next year. (allocate在劍橋學術詞典中的解釋© Cambridge Unive...
- 3how to use windbg track memory allocated with VirtualAlloc?
- 4be allocated with | English examples in context - Ludwig.guru
High quality example sentences with “be allocated with” in context from reliable sources - Ludwig...
- 5Allocate Definition & Meaning - Merriam-Webster
1 : to divide and give out for a special reason or to particular people or things Funds were allo...