this post was submitted on 27 Oct 2023
2 points (100.0% liked)

C & C++

885 readers
1 users here now

founded 5 years ago
MODERATORS
 

I am writing a unit test and mocking library in C and I want to set the call stack memory to some pre determined value like memset. I want to do this before the test function is called so the test writer can verify they aren't using uninitialized memory in their tests. Is there any somewhat portable way to do this?

you are viewing a single comment's thread
view the rest of the comments
[–] deaf_fish@lemm.ee 1 points 1 year ago* (last edited 1 year ago)

Ok, this is an option and I hate it, but I am open if to notes if anyone has any. I think I might have to inline assembly. Here is my first attempt:

static
void rmFillStackData(size_t bytes, unsigned char value)
{
   if(bytes > 0)
   {
      // If anyone knows a better way to do this, please let me know
#if defined(__x86_64__) || defined(_M_X64) || defined(i386) || defined(__i386__) || defined(__i386) || defined(_M_IX86)
      // This works by assuming that the last parameter "value" is at the bottom
      // of the stack. So writing below it is fine. This also assumes the 
      // address of the stack pointer get smaller as the stack gets fuller.
      asm volatile ("loop:\n\t"
                    "mov %1,(%2)\n\t"
                    "dec %2\n\t"
                    "dec %0\n\t"
                    "jne loop\n"
                    : /* No Outputs */
                    : "r"(bytes),"r"(value),"r"(&value)
                    : "memory");
#endif
   }
}