I have a function prototype which provides me with the result I’m after:
#include <stdio.h>
#include <string.h>
int main ()
{
char * pch;
char str[] = " 81.243.230.174, 10.1.0.102";
pch = (char*) memchr (str, ',', strlen(str));
char * tch;
memcpy (tch, str, pch-str);
if (pch!=NULL){
printf ("',' found at position %ld.\n", pch-str);
printf ("XFF: %s\n", tch);
} else {
printf ("',' not found.\n");
}
return 0;
}
Returns the following:
$>’,’ found at position 15.
$>XFF: 81.243.230.174
I want to process the output of VRT_GetHdr from libvcl as str above, as follows:
char * pch;
char str[] = VRT_GetHdr(sp, HDR_REQ, "\023X-FF:");
pch = (char*) memchr (str, ',', strlen(str));
char * xff;
memcpy (xff, str, pch-str);
if (get_country_code)
VRT_SetHdr(sp, HDR_REQ, "\017X-Country-Code:", (*get_country_code)(xff), vrt_magic_string_end);
VRT_GetHdr returns a char pointer and the compiler complains about an “invalid initializer.”
If I change the assignment of
char str[]
to
char *str
, varnish dies at runtime (probably with a segfault).
How can I get the expected result from my inline C, without using the above pointer to array mess?
You can’t.
The initializer expression must be literal to provide a compile-time size, and your function call isn’t.
You might be able to get around this using C99’s automatic arrays, but it’s maybe easier and cleaner to just use a dynamically allocated array (using
malloc(), orstrdup()if you have it).Or even a static limit that is “large enough”, if you have reason to believe there is some limit to the length of the return value.
Your code reads a bit like a re-implementation of
strtok(), perhaps you can use it directly?