Quantcast
Channel: GameDev.net
Viewing all articles
Browse latest Browse all 17825

Weird behavior for a function with optimizations turned on

$
0
0
I have a function which returns the name of the processor for X64 based on __cpuid() intrinsic. When i run that function without optimizations its fine and works correct, but when i compile and run it with O2 for example then the compiler does weird things. The branch for detecting if "destBuffer" is null is totally changed, no comparison will be made and "destLen" will never be set. The result is that PushMemory_Internal() gets a totally garbage size and may return nullptr. What did i wrong? The compiler definitily rearranged it a lot, so its hard to follow. Basically the function has two modes, one with a given destBuffer and its max length and one without any dest buffer at all - so in this case we stack allocate the memory we need for worst case size. static char *GetProcessorName(char *destBuffer = nullptr, const uint32_t maxDestBufferLen = 0); static char *GetProcessorName(char *destBuffer, const uint32_t maxDestBufferLen) { constexpr uint32_t cpuBrandBufferSize = 0x40; uint32_t destLen = maxDestBufferLen; if (destBuffer == nullptr) { destLen = cpuBrandBufferSize + 1; destBuffer = (char *)malloca(destLen); } assert(destBuffer != nullptr); assert(destLen >= (cpuBrandBufferSize + 1)); int cpuInfo[4] = { -1 }; char cpuBrandBuffer[cpuBrandBufferSize] = {}; __cpuid(cpuInfo, 0x80000000); uint32_t extendedIds = cpuInfo[0]; // Get the information associated with each extended ID. // Interpret CPU brand string. for (uint32_t i = 0x80000000; i <= extendedIds; ++i) { __cpuid(cpuInfo, i); if (i == 0x80000002) { CopyMemory(cpuInfo, cpuBrandBuffer, sizeof(cpuInfo)); } else if (i == 0x80000003) { CopyMemory(cpuInfo, cpuBrandBuffer + 16, sizeof(cpuInfo)); } else if (i == 0x80000004) { CopyMemory(cpuInfo, cpuBrandBuffer + 32, sizeof(cpuInfo)); } } // Copy result back to the dest buffer uint32_t sourceLen = strlen(cpuBrandBuffer); strncpy(destBuffer, cpuBrandBuffer, sourceLen); return(destBuffer); } Thanks in advance, Final

Viewing all articles
Browse latest Browse all 17825

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>