What does s [-1] = 0 mean?

I am studying the strtok function code from bsd libc, when I ran it on my machine, the program received a signal SIGSEGVin s[-1] = 0. Here is a link to the code.

Is he s[-1] = 0right?

This is my code:

#include <stdio.h>
#include <stdlib.h>
#include "strtok.c"

int main(int argc, char* argv[]) {
    char* str = "xxxx xxxyy fdffd";
    const char* s = " ";

    char* token = strtok(str, s);

    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, s);
    }

    return 0;
}
+4
source share
6 answers
s[-1]

Expands to:

*( s - 1 )

Therefore, if the result indicates a valid memory, the code is defined.

+6
source

This is normal, because s- this is the pointer that we see from the draft of the C99 standard, which E1[E2] is identical to (*((E1)+(E2)))from the section 6.5.2.1Subscriber in the array says (my attention):

, [], . [] E1 [E2] (* ((E1) + (E2))). - , +, E1 - (, ), E2 - , E1 [E2] E2- E1 ( ).

s , , , , undefined.

+3

s[-1] , , s.

C, s[-1] *(s-1). :

  • s-1. , s, , s+1 s.
  • , lvalue .

, s[-1] = 0 0 , s.

s[-1] , s ( , ), s . ( , s , , - .)

+3

, s ++, (s + 1) -1.

+1

s[-1] = 0 "" "", s.

s[-1] = 0 .

+1

, , FreeBSD strtok(3) .

s a char*; s[-1] , , s - NUL.

Can we see your actual code calling strtok(3)? Probably the problem is in your set, so to speak. Also, have you read the manual page?

The first time it is called strtok(), you must specify str; subsequent calls wishing to receive further tokens from one line should instead pass a null pointer. A separator string sepmust be provided each time and may vary between calls.

0
source

Source: https://habr.com/ru/post/1523604/


All Articles