By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,984 Members | 1,092 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,984 IT Pros & Developers. It's quick & easy.

segmentation fault when comparing string with NULL in strlen

P: 1

i am getting segmentation fault with the below code.

size_t strlen(const char *str) {
const char *str1 = str;
if (str == NULL)

while (*str)

return(str - str1);

I am getting segmentation fault in the line if(str == NULL). str has the value "P\302n+K\177"
Please suggest.
Aug 8 '16 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 5K+
P: 9,197
Post the code that calls this function.

This function assumes a non-zero str contains a valid address.

I want to see the call to verify that str is not screwed up before the call.
Aug 8 '16 #2

Expert 100+
P: 2,396
Depending on the details of your debugger, it might be difficult to distinguish if the exception occurs for the str1=str assignment or the if statement on the next line. Suggest you separate them a little more:
Expand|Select|Wrap|Line Numbers
  1. ...
  2. const char *str1;
  3. if(str==NULL)
  4.     return(0);
  5. str1 = str;
  6. ...
Aug 9 '16 #3

Post your reply

Sign in to post your reply or Sign up for a free account.