Perché il risultato è diverso usando strtok_r in Mac e Ubuntu

Oct 10 2020

Sto praticando c Lang strtok_r ().
Ecco il mio codice.

#include<stdio.h>
#include<string.h>
#include<unistd.h>

int main(int argc, char** argv){
    char* ptr = NULL;
    char* next[2] = {0};
    char delimiter[4];
    int now = 1;

    strcpy(delimiter, " \t");

    // check argc number
    if(argc != 3){
        printf("usage : ./test {string} {string}\n");
        return -1;
    }

    ptr = strtok_r(argv[1], delimiter, &next[1]); 
    printf("ptr : %s, next : %s\n", ptr, next[1]);
    
    ptr = strtok_r(argv[2], delimiter, &next[2]); 

    while((ptr = strtok_r(NULL, delimiter, &next[1])) != NULL){
        printf("%d : %s, next : %s\n", ++now, ptr, next[1]);
    }
    
    return 0;
}

Penso che il risultato del codice sarà

$ a.out "I'm test now" "Hello every"
ptr : i'm, next : test now
2 : test, next : now
3 : now, next : (null)

Il mio risultato mac è quello.

Ma il mio ubuntu20.04 (immagine Docker) non lo è.
Ecco il risultato dell'esecuzione su Ubuntu.

$ a.out "i'm test now" "hello every"
ptr : i'm, next : test now
2 : test now, next : 

Perché il risultato è diverso in Mac e Ubuntu

Risposte

2 user3629249 Oct 10 2020 at 20:58

riguardo a:

char* next[2] = {0};
...
ptr = strtok_r(argv[1], delimiter, &next[1]); 
printf("ptr : %s, next : %s\n", ptr, next[1]);

ptr = strtok_r(argv[2], delimiter, &next[2]); 

while((ptr = strtok_r(NULL, delimiter, &next[1])) != NULL){ 

l'array: nextha 2 elementi. Pertanto, gli indici validi in quell'array sono 0 e 1. Non 1 e 2.

Il codice inserito sta accedendo oltre la fine nextdell'array. Il risultato è un comportamento indefinito.

Nota: gli indici validi in un array sono 0 ... (numero di elementi nell'array -1)