0

This was a question from an exam :
does this code always works ?
the answer is : the if statement checks if the virtual address of 'str' is pointed to the beginning of a page, only then the strcpy should be executed and it will work because the whole page is accessible by this process.
Can anyone please explain me this ambiguous answer ? thank you very much

int main () {
   char *str ;
   str = (char*) malloc (sizeof(char)*4);
   if ( ((int)str) & 0x00000FFF) != 0) return 0;
   strcpy ( str ,"1234567890") ;
   printf ("str=%s", str ) ;
   return 0;
}
Rawhi
  • 6,155
  • 8
  • 36
  • 57

1 Answers1

0

As far as the C standard goes: This does not work, undefined behavior.

As far as practical reality goes: This does not work. Real malloc() implementations can and do put more than one object per page. While the OS won't catch any error, you'll have overwritten other allocated objects and malloc() internal structures.

user12864
  • 581
  • 4
  • 7