Skip to contentSkip to conversation

Example code at the manpage of strtok produces segmentation fault.

DISCUSSION Alejandro Colomar 1 participant 3 messages Mar 11, 2023 3 messages not in the archive Man-pages: manual pages for Linux -- Sections 2, 3, 4, 5, and 7

lore
Share & tools
lore

A message that is not in the archive (sent off-list or not yet received): [email protected]

#1 lore raw

Hi Leon,

Quoted 15 lines · Leon Breidt

Dear Mr. Kerrisk, dear Mr. Colomar,

I am a student at the university of applied sciences of Kaiserslautern, Germany. I am currently working on some code for a class using c, in which I needed to split some char arrays.

I tried to understand the functionality of strtok using the manual and found a code example which seemed helpful. However, simply copy-pasting it, compiling it and executing the example usage produces a segmentation fault. Particulary annoying is this as the code was used in answers on stackoverflow, and continues to spread its false message from there...

Steps to reproduce:

- execute: man strtok

- copy the code from the section "EXAMPLES"

Quoted 8 lines

- paste it into a new file "main.c"

- execute "gcc main.c"

- execute the example usage given in the manual: ./a.out 'a/bbb///cc;xxx:yyy:' ':;' '/'

=> Segmentation fault instead of the output described in the man page.

I can't reproduce that[1]. Could you please confirm if you can build and run the program as shown below using the build system (Makefile)?

Quoted 3 lines

I would be more than happy to create a better usage example, but I am uncertain how to submit a patch via E-Mail. I've never done this before. Will it be sufficient to send you the code of a new, hopefully better/fixed version via E-Mail?

Sure, if you can't send a patch, something like that should be good.

Nevertheless, I encourage you to learn to send patches through email. It's not so difficult. I guess you know how to use git(1). If you do, the simplest thing you can do is to paste the output of git diff (or a similar command) into an email. Once you can do that, you can learn git-format-patch(1) and git-send-email(1), which would allow me to apply the patch directly from the email, without having to copy+paste, but git-diff(1) should be enough for a start.

Quoted 5 lines

Kind regards,

Leon Breidt

Kind regards,

Alex

[1]:

alx@debian:~/src/linux/man-pages/man-pages/main$ make build-src -ij >/dev/null 2>&1
alx@debian:~/src/linux/man-pages/man-pages/main$ make build-src -tj
alx@debian:~/src/linux/man-pages/man-pages/main$ touch man3/strtok.3
alx@debian:~/src/linux/man-pages/man-pages/main$ make build-src V=1
MKDIR	tmp/src/man3/strtok.3.d
mkdir -p tmp/src/man3/strtok.3.d
touch tmp/src/man3/strtok.3.d
SED	tmp/src/man3/strtok.3.d/strtok.c
<man3/strtok.3 \
sed -n \
	-e '/^\.TH/,/^\.SH/{/^\.SH/!p}' \
	-e '/^\.SH EXAMPLES/p' \
	-e "/^\... SRC BEGIN (strtok.c)$/,/^\... SRC END$/p" \
| man -P cat -l - \
| sed '/^[^ ]/d' \
| sed 's/^       //' \
Quoted 1 line

tmp/src/man3/strtok.3.d/strtok.c

CC tmp/src/man3/strtok.3.d/strtok.o
cc -c -isystem /usr/include/bsd -DLIBBSD_OVERLAY -std=gnu17 -Wall -Wextra -Wstrict-prototypes -Wdeclaration-after-statement -Werror -Wno-error=unused-parameter -Wno-error=sign-compare -Wno-error=format -Wno-error=uninitialized -o tmp/src/man3/strtok.3.d/strtok.o tmp/src/man3/strtok.3.d/strtok.c
LD tmp/src/man3/strtok.3.d/strtok
cc -std=gnu17 -Wall -Wextra -Wstrict-prototypes -Wdeclaration-after-statement -Werror -Wno-error=unused-parameter -Wno-error=sign-compare -Wno-error=format -Wno-error=uninitialized -Wl,--as-needed -Wl,--no-allow-shlib-undefined -Wl,--no-copy-dt-needed-entries -Wl,--no-undefined -o tmp/src/man3/strtok.3.d/strtok tmp/src/man3/strtok.3.d/strtok.o -lc -lbsd

alx@debian:~/src/linux/man-pages/man-pages/main$ tmp/src/man3/strtok.3.d/strtok
Usage: tmp/src/man3/strtok.3.d/strtok string delim subdelim
alx@debian:~/src/linux/man-pages/man-pages/main$ tmp/src/man3/strtok.3.d/strtok a.s,q.w,z.x . ,
1: a
	 --> a
2: s,q
	 --> s
	 --> q
3: w,z
	 --> w
	 --> z
4: x
	 --> x
alx@debian:~/src/linux/man-pages/man-pages/main$ tmp/src/man3/strtok.3.d/strtok 'a/bbb///cc;xxx:yyy:' ':;' '/'
1: a/bbb///cc
	 --> a
	 --> bbb
	 --> cc
2: xxx
	 --> xxx
3: yyy
	 --> yyy

If it crashes for you running these commands, there might be something wrong either in the page or in your system.

If it works, then the problem is probably in the way you copied it. Do you see any warnings from the compiler?

Signature · 2 lines
<http://www.alejandro-colomar.es/>
GPG key fingerprint: A9348594CE31283A826FBDD8D57633D441E25BB5

A message that is not in the archive (sent off-list or not yet received): [email protected]

#3 lore raw
Quoted 2 lines · Leon Breidt

Hello Alex,

Hello Leon,

Quoted 2 lines

unfortunately it seems I did not receive the Makefile you wanted me to use, trying to assemble it from the console output you provided me failed. Probably my lack of experience with make doesn't benefit me either...

Sorry, I didn't specify. I meant the Makefile in the man-pages' git repository.

Quoted 2 lines

I have cloned the man-pages repository from git and looked in the Makefile there, but there is no build-src target specified there as well.

That Makefile is rather short, and as you say has no 'build-src' target. However, you might have noticed it has many 'include's at the end of the file, which provide the actual functionality (but you don't need to care about them; just run make build-src from the root of the repo).

The main Makefile only contains the 'all' and 'help' targets. BTW, if you run make help, you'll see a full list of targets you can run.

Quoted 10 lines

Could you send me the text content of the makefile you want me to use, it seems attached files don't make it all the way?

To address your other question, I have tried a simple copy-paste with ctrl-c, ctrl-v from the manual page in my terminal, as well as from the website at https://man7.org/linux/man-pages/man3/strtok_r.3.html

I do indeed see compiler warnings, you will find them below:

breidt@STUDENT-III:~/tmp$ gcc main.c

You should _always_ compile with -Wall and -Wextra:

   $ gcc -Wall -Wextra main.c
Quoted 19 lines

main.c: In function ‘main’:
main.c:17:28: warning: initialization of ‘int’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversion]
17 | for (int j = 1, str1 = argv[1]; ; j++, str1 = NULL) {
| ^~~~
main.c:17:49: warning: assignment to ‘int’ from ‘void *’ makes integer from pointer without a cast [-Wint-conversion]
17 | for (int j = 1, str1 = argv[1]; ; j++, str1 = NULL) {
| ^
main.c:18:26: warning: passing argument 1 of ‘strtok_r’ makes pointer from integer without a cast [-Wint-conversion]

   18 |         token = strtok_r(str1, argv[2], &saveptr1);
      |                          ^~~~
      |                          |
      |                          int
In file included from main.c:3:
/usr/include/string.h:366:41: note: expected ‘char * restrict’ but argument is of type ‘int’
  366 | extern char *strtok_r (char *__restrict __s, const char *__restrict __delim,
      |                        ~~~~~~~~~~~~~~~~~^~~
Quoted 1 line

I have also attached the exact c file I am compiling with "gcc main.c". Lets hope it gets through.

Now I see the problem. It was a bug accidentally introduced in man-pages-5.09:

---

$ git log -1 88893a773cbd219f08cc3ae34fffe079d89a120d
commit 88893a773cbd219f08cc3ae34fffe079d89a120d
Author: Michael Kerrisk <[email protected]>
Date:   Sat Sep 5 17:18:10 2020 +0200

sprof.1, eventfd.2, execve.2, futex.2, getdents.2, mprotect.2, open_by_handle_at.2, recvmmsg.2, sched_setaffinity.2, CPU_SET.3, backtrace.3, bsearch.3, dl_iterate_phdr.3, dlinfo.3, duplocale.3, encrypt.3, envz_add.3, fopencookie.3, getaddrinfo.3, getaddrinfo_a.3, getdate.3, getgrent_r.3, getgrouplist.3, getifaddrs.3, getprotoent_r.3, getservent_r.3, hsearch.3, mallinfo.3, malloc_info.3, mbstowcs.3, mtrace.3, pthread_create.3, pthread_getcpuclockid.3, pthread_setaffinity_np.3, qsort.3, rand.3, strcat.3, strtok.3, tsearch.3, wordexp.3, core.5, aio.7, inotify.7, sock_diag.7, unix.7, user_namespaces.7: Use C99 style to declare loop counter variables

Rather than:

sometype x;

for (x = ....; ...)

use

for (sometype x = ...; ...)

This brings the declaration and use closer together (thus aiding readability) and also clearly indicates the scope of the loop counter variable.

$ git describe --contains 88893a773cbd219f08cc3ae34fffe079d89a120d
man-pages-5.09~442
$ git show man-pages-5.09
tag man-pages-5.09
Tagger: Michael Kerrisk <[email protected]>
Date:   Sun Nov 1 21:08:55 2020 +0100

This is man-pages-5.09

---

It was fixed in man-pages-6.00:

---

$ git show f091d3e26e4cdef9ecc632d6f4bd94dc16fce43e
commit f091d3e26e4cdef9ecc632d6f4bd94dc16fce43e
Author: Stephen Kitt <[email protected]>
Date:   Sat Jan 8 16:43:04 2022 +0100

strtok.3: Fix j/str1 declaration

for (int j = 1, str1 = argv[1]; ...

declares two variables of type int, j and str1; the pre-existing char * str1 isn't used. This causes compiler warnings. Declaring j outside the loop fixes everything.

man3/strtok.3 +2 -1
index aec914094..06e9688b6 100644
@@ -255,6 +255,7 @@ .SS Program source
 {
     char *str1, *str2, *token, *subtoken;
     char *saveptr1, *saveptr2;
+    int j;
 
     if (argc != 4) {
         fprintf(stderr, "Usage: %s string delim subdelim\en",
@@ -262,7 +263,7 @@ .SS Program source
         exit(EXIT_FAILURE);
     }
 
-    for (int j = 1, str1 = argv[1]; ; j++, str1 = NULL) {
+    for (j = 1, str1 = argv[1]; ; j++, str1 = NULL) {
         token = strtok_r(str1, argv[2], &saveptr1);
         if (token == NULL)
             break;
$ git describe --contains f091d3e26e4cdef9ecc632d6f4bd94dc16fce43e
man-pages-6.00~1122
$ git show man-pages-6.00
tag man-pages-6.00
Tagger: Alejandro Colomar <[email protected]>
Date:   Sun Oct 9 18:48:44 2022 +0200

man-pages-6.00 - manual pages for GNU/Linux

I've released man-pages-6.00. The release tarball will soon be available on <kernel.org>.

This release resulted from patches, bug reports, reviews, and comments from around 145 contributors. The release includes around 1245 commits, and changed all of the pages.

The most notable of the changes in man-pages-6.00 are the following:

- A new set of man dirs: man2type/, man3const/, man3head/, and man3type. These hold new pages and pages splitted from system_data_types(7), which had become too big in the recent releases.

- An improved build system, which allows running linter programs that check the correctness of both the man(7) source and the C programs in EXAMPLES.

- A new LIBRARY section (mostly in sections 2 and 3). There have also been other important changes to the title and other sections, such as the removal of the COLOPHON.

- We have added several new pages documenting new kernel features, such as landlock(7) and memfd_secret(2).

Especial mention to наб, with 58 commits to this release.

Thank you all for contributing. Especially to those in the groff@ mailing list who helped me a lot in this release, and to Michael (mtk). -----BEGIN PGP SIGNATURE-----

iQIzBAABCgAdFiEE6jqH8KTroDDkXfJAnowa+77/2zIFAmNC+6wACgkQnowa+77/ 2zJEnQ/9GErYhSvR/SG1NUencHSg5pb2q0O/rVnavPpnK1CTBGWlDlF6a0d5+7RZ zlP1BM289WN6xIIb4PyeobpKfMO0WUgRliKJPKCBz8lsiCIB0ZxrcD6o+rDeKvXK g+eP6ofYYEZ9sTYWZR1Id2LYbwir4JO4Pp3O2xZA1W0XJJh8zN/tMMQwTxQfpBCF I2K6vGKipT2/ueTu0qZ7A6lswdPSTwbeuFJjGV6VneI4yy/ID3KHgrU++3l/wq1h sseEPNT5E+y+bhwA7958v/yjl9Sbn6ebvVFoAJakylv95UWPWprqFBVks2az4Xz+ oXAmcRdKQ1aWQwD+6MrwLqjKsO3qvlgxJzREDFr8ySUmiPnyp7PJ160XtvqP2zu2 elyvPPsu4YvGIO9lojXxAT66kY4XXg6tKgdaJac2QXt/dl/C9Q+Ni9MDuyLbnbGb RLlQLjCpjsrpIaa+xniJzrZqh9VjbxDvG2YliyhvLjdGLoV3YQjOgIoYWJctaIw3 hFD6XLIGWrKXQ0uw26zGhYbXYd8z7WY5r36h5izdF9SeXP0Bgo1hw9NR6UNFbqND nFXlIjyYBLdLYF2JWrqMdU0/qTJwRzSQ9feqd3KXTQIG21legeLUrG885408pUyu wsCCIXqKuIpysAjHyjwWVCFvGDr4CQ5qtE1fYTrFFmHUFruj89Y= =uOhR
-----END PGP SIGNATURE-----

---

The bad news is that the <man7.org> online pages have not been updated since man-pages-5.13 (Aug 2021). You're probably using an old distro that still has some old pages too.

Quoted 4 lines

Kind regards,

Leon

Kind regards,

Alex

Signature · 2 lines
<http://www.alejandro-colomar.es/>
GPG key fingerprint: A9348594CE31283A826FBDD8D57633D441E25BB5

A message that is not in the archive (sent off-list or not yet received): [email protected]

#5 lore raw

Hi Leon,

Quoted 6 lines · Leon Breidt

Hello Alex,

okay, that seems to explain the problems. I have corrected my usage of strtok_r in the meantime, so my original issue is resolved as well.

Quoted 6 lines

It seems the git repo was also last updated two years ago. Therefore it does not have the build-src target specified at all, which explains why my build attempts failed.

https://github.com/mkerrisk/man-pages

<https://github.com/mkerrisk/man-pages>

That was a mirror that Michael ran on Github. When Michael left the project a few years ago, his mirror wasn't updated anymore.

Quoted 2 lines

Perhaps I used the wrong repo?

The original repository is
<https://git.kernel.org/pub/scm/docs/man-pages/man-pages.git>.

Quoted 1 line

Since it is run by the other maintainer of man-pages, this seems rather odd.

He left the project a couple of years ago, since he was very busy with his own business. I didn't yet update the website
<https://www.kernel.org/doc/man-pages/index.html>, so it still shows him as comaintainer. The only source of truth now is the git repository, since I don't have the time to fix other stuff.

You can consider the README the starting point for documenting the organization of the project:
<https://git.kernel.org/pub/scm/docs/man-pages/man-pages.git/tree/README>

Quoted 1 line

Even though it is not necessary anymore, I would like to test the new code, just to get familiarized with stuff like that.

Sure, just clone that git repo from <kernel.org>, read the README, then read INSTALL and CONTRIBUTING, and run make help to see a list of available targets.

Quoted 5 lines

Kind regards,

Leon

Kind regards,

Alex

Signature · 2 lines
<http://www.alejandro-colomar.es/>
GPG key fingerprint: A9348594CE31283A826FBDD8D57633D441E25BB5