-2

v is read from stdin
v2 is not but they are identical.

char *v;
v = (char *) malloc(1);
fread(v,i,1,stdin);
printf("%s",v);

prints:

a=aaa&b=ooo%3C%2Ftest%3Eooo

v2 is identical to v

char *v2 = "a=aaa&b=ooo%3C%2Ftest%3Eooo"

let's try to PARSE what is after "b=" from "v"

const char *PATTERN1 = "b=";
const char *PATTERN2 = "&";

char *END = NULL;
char *START = strstr(v, PATTERN1);

if (START) {
START = START + strlen(PATTERN1);
char * END = strstr(START, PATTERN2);

if (!END){
ENDm = START + strlen(START);
}

TARGET = malloc(END - START + 1);
memcpy(TARGET, START, END - START);
TARGET[END - START] = '\0';
}

printf("--%s--",TARGET);

result :

--abc%3C%2Ftest%!--

it is missing some stuff towards the end. ( also has an extra "!" )

Now let's use the same code above on "v2"

--abc%3C%2Ftest%3Eabc--

this time nothing is missing

1 Answers1

5

You cannot store a string in an array of 1 characters. The only string you can store is "" (the empty string) since that requires exactly one character for the '\0' terminator.

Your code suffers from undefined behavior, so it cannot be reasoned about beyond that.

unwind
  • 391,730
  • 64
  • 469
  • 606