问题
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