c - fopen() corrupts the path argument -


i'm experiencing strange bug when passing variable fopen() opposed string literal. here's offending piece of code:

file *rc; ... rc = fopen ( path, "a" ); 

path defined this:

char path [ sizeof ( getenv ("home") ) + 8]; /* 8 length of "/.bashrc" , "/.tcshrc" .*rc files longest names */ strcpy ( path, getenv ("home") ); ... if ( <check shell> ) {     strcat ( path, "/.*rc" ); } 

here's output prior calling fopen():

${home}/.*rc (for example /home/user/.bashrc) 

and after:

"$home" + square + \t + "rc" 

... use imagination.

why fopen() altering path? doing wrong or known bug (i did not find online , man pages don't mention it?)

you need use strlen(getenv("home")), not sizeof(getenv("home")). getenv returns pointer, not array (it's not possible return array in c), sizeof returning size of pointer, 4.

also, need allow space trailing 0 byte strings have. if you'll appending 8-character strings "/.bashrc", need add 9 length of home directory when allocate path. should be:

char path [ strlen ( getenv ("home") ) + 9]; 

Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -