Interesting printf() glitch in C while converting bases -


i have following code in c:

char* getbase(unsigned int a, int base) {     char buffer[33];      char digits[] = "0123456789abcdef";      if(base < 2 || base > 16) {         printf("invalid base");         return null;     }      char* cn = &buffer[sizeof(buffer) - 1];     *cn = '\0';      {         cn -= 1;         *cn = digits[a % base];         /= base;     } while(a > 0);      printf("\n"); //here      return cn; }  int main() {     printf("%s", getbase(8, 2));     return 0; } 

as can see, takes base 10 number, , converts between base 2 , base 16. works unless comment out line marked //here. reason, if don't have printf statement, doesn't work. have no idea why happening, explanations?

undefined behavior cause quite weird behavior.

you returning cn in function getbase, pointer points somewhere in local automatic array buffer.

to fix problem, can make buffer static, or use dynamic allocation.


Comments

Popular posts from this blog

command line - Use qwinsta in PowerShell ISE -

java - Incorrect order of records in M-M relationship in hibernate -

Python website log in: BIG-IP can not find session information in the request -