simple problem

J

J Wang

the c code as follows:

#include <stdio.h>
#include <stdlib.h>

int main()
{
printf("%s\n", getenv("NAME"));
return 0;
}

Segmentation Fault

why?

cheers,
 
L

Leor Zolman

the c code as follows:

#include <stdio.h>
#include <stdlib.h>

int main()
{
printf("%s\n", getenv("NAME"));
return 0;
}

Segmentation Fault

why?
NULL.
-leor


cheers,
 
M

Mike Wahler

J Wang said:
the c code as follows:

#include <stdio.h>
#include <stdlib.h>

int main()
{

char *name = getenv("NAME");
printf("%s\n", getenv("NAME"));

if(name)
printf("%s\n", name);
else
printf("%s\n", "getenv() returned NULL");
return 0;
}

Segmentation Fault

why?

Most likely you tried to dereference a NULL pointer.

*Always* check the return value of a function
which can fail.

-Mike
 
M

Martin Ambuhl

J said:
the c code as follows:

#include <stdio.h>
#include <stdlib.h>

int main()
{
printf("%s\n", getenv("NAME"));
return 0;
}

Segmentation Fault

why?

Perhaps "NAME" is not defined in the environment, so getenv() returns
NULL and your attempt to dereference it is illegal. We just had this a
couple of days ago. That you did not see it shows that you violated
usenet etiqutte by posting without following the newsgroup first. You
probably didn't check the FAQ either.
 
B

Barry Schwarz

the c code as follows:

#include <stdio.h>
#include <stdlib.h>

int main()
{
printf("%s\n", getenv("NAME"));
return 0;
}

Segmentation Fault

why?

getenv is allowed to return NULL. You need to check for that
situation before dereferencing the return value.


<<Remove the del for email>>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,141
Messages
2,570,817
Members
47,362
Latest member
ChandaWagn

Latest Threads

Top