atoi(getenv(“MYVAR”))

Posted in Technicalon May 28, 2008

These are mostly personal notes. I’m not sure if they will make sense to others.

I had a problem with a line of code like this:
int x = atoi(getenv("MYVAR"));

If this line was in daemon-ized code started at init level 2, it would segfault. (I’m not sure if these conditions are necessary, but those were my conditions).

getenv("UNKNOWN_VAR") == NULL
atoi(NULL) should == 0

But for some reason, things were segfaulting. I corrected the problem with:
if (getenv("MYVAR") == NULL) int x = 0;
else int x = atoi(getenv("MYVAR"));

2 Comments

alex

May 28th, 2008 at 9:31 pm

That’s pretty weird. Is it only runlevel 2? If that’s the case it is probably an environment variable that depends on some higher-level initializations. In which case if you really wanted to know what it depended on you could start fooling around with your initscripts in your VM. You could probably narrow it down to a few suspicious ones and figure it out fairly quick.

jacob

May 29th, 2008 at 7:20 am

I thought it might have been the getenv, but getenv(“PATH”) worked, and I verified that getenv(“UNKNOWN”) properly returned NULL. So I think its the atoi(NULL) that is the problem.

It might not work at other runlevels as well, but I didn’t test those.

Comment Form

Categories