Please notice the static variable selection
. I am testing if the selection is assigned the correct char string within the different scope.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char* selection;
static char* sel_item(char* text)
{
char* pch;
char buf[80];
strcpy(buf, text);
pch = strtok(buf, " ");
return pch;
}
static int display_ecnt_codes(char* text)
{
char buf[80];
strcpy(buf, text);
selection = sel_item(buf);
// why if I output the selection here, the selection is random char, not the correct char "SRFPRO".
// printf("display_ecnt_codes: %s\n", selection);
}
int acode_prockey()
{
char text[] = "SRFPRO - Surface Protection (DealerProduct)";
display_ecnt_codes(text);
// why if I output the selection here, it prints the correct char string "SRFPRO".
// what's the difference between this scope and the above scope?
printf("acode_prockey: %s\n", selection);
}
int main ()
{
acode_prockey();
// it will output SRFPRO, the first token of the char text[].
printf("main: %s\n", selection);
}
I am hoping someone can explain the global static varible "selection". When I printf it inside the function "display_ecnt_codes", it outputs the random char. If I do not printf it inside the function, it output the correct char in the main function.
In the following function, you are returning a pointer that is not valid after the function returns.
static char* sel_item(char* text)
{
char* pch;
// An array on the stack
char buf[80];
strcpy(buf, text);
// A pointer to some element of the array.
pch = strtok(buf, " ");
// Returns a pointer that is not valid after the function returns.
return pch;
}
Later on, you use that invalid pointer which is stored in selection
. Your program exhibits undefined behavior because of that.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments