Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

strncpy + strlen is pointless #312

Merged
merged 1 commit into from
Oct 7, 2018
Merged

strncpy + strlen is pointless #312

merged 1 commit into from
Oct 7, 2018

Conversation

orestisfl
Copy link
Member

No description provided.

strlen already assumes that the string is NULL-terminated.

Fixes -Wstringop-overflow warning
orestisfl added a commit to orestisfl/i3 that referenced this pull request Oct 3, 2018
strlen already assumes that the string is NULL-terminated.

Like in i3/i3status#312 but for whatever reason
gcc didn't warn about this here.
@TwentyFourD
Copy link
Contributor

I've just come across a similar occurrence (but with strncmp) in i3status.h:

#define BEGINS_WITH(haystack, needle) (strncmp(haystack, needle, strlen(needle)) == 0)

Does this fall into the same category?

@orestisfl
Copy link
Member Author

orestisfl commented Oct 6, 2018

No, that's correct. Example:

char *a = "Hello World!";
char *b = "Hello";
printf("%d %d\n", strcmp(a, b), strncmp(a, b, strlen(b)));

@TwentyFourD
Copy link
Contributor

Ah - yes. I was actually experimenting with:

bool begins_with(const char *haystack, const char *needle) {
while (*needle)
if (*needle++ != *haystack++)
return false;
return true;
}

which works, I think.

@orestisfl
Copy link
Member Author

Yes, this works. But we wouldn't want to replace something using standard string comparison functions with our own implementation. It's not easier to understand and it's not faster either: the glibc implementation uses SSE optimizations and the strlen call should be replaced by the compiler.

@stapelberg stapelberg merged commit 494efd4 into i3:master Oct 7, 2018
stapelberg pushed a commit to i3/i3 that referenced this pull request Oct 7, 2018
strlen already assumes that the string is NULL-terminated.

Like in i3/i3status#312 but for whatever reason
gcc didn't warn about this here.
@orestisfl orestisfl deleted the strcpy branch October 7, 2018 18:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants