Revanth Tv
Revanth Tv

Reputation: 53

Segmentation fault core (Core dumped) in C

I am running a code which is throwing me segmentation fault (Core dumped) error.

I have a function which returns an unsigned integer data type of strlen which accepts a char datatype of a de-referenced variable pointer or a variable of char datatype as an input argument.

I know that i am incrementing a const char pointer variable which is not a great practice. I read that incrementing a point and de-reference it is a good option over incrementing the data to which the pointer variable is pointing to.

I mean *s++; to *(++s); How different are they? Or they do same operation? I see segmentation fault (core dumped) on both operations. Or may be i should only increment the the pointer ? That is 's'

size_t strlen(const char *s)
{
  size_t len = 0;

  while (*(++s) && ++len);

  return len;
}

Upvotes: 0

Views: 342

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

This while loop in general is incorrect

while (*(++s) && ++len);

if the user will pass an empty string then the terminating zero character '\0' will be skipped in the first iteration of the loop due to incrementing the pointer s. That can result in undefined behavior.

Just rewrite the while loop the following way

while ( *s++ ) ++len;

Pay attention to that the pointer s shall point to a string: a sequence of characters terminated with the zero character '\0'.

The difference between these two expressions *++s and *s++ is that in the first case the pointer at first is incremented and the result value is dereferenced. While in the second case the original pointer at first is dereferenced and only after that the side effect of incrementing is applied to the pointer.

Upvotes: 2

Related Questions