Why is different result using strtok_r in Mac & Ubuntu

时光怂恿深爱的人放手 提交于 2020-12-15 19:35:24

问题


I'm practice c Lang strtok_r().
Here is my code.

#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;
}

I think that code result will be

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

My mac result is that.

But my ubuntu20.04(Docker image) isn't.
Here is result of execute on Ubuntu.

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

Why result is different in Mac & ubuntu


回答1:


regarding:

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){ 

the array: next has 2 elements. Therefore, the valid indexes into that array are 0 and 1. Not 1 and 2.

The posted code is accessing beyond the end of the next array. The result is Undefined Behavior.

Note: the valid indexes into an array are 0...(number of elements in array -1)



来源:https://stackoverflow.com/questions/64290928/why-is-different-result-using-strtok-r-in-mac-ubuntu

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!