我有以下(简化的)简单应用程序,它是用 line 构建的:
gcc -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -D_GNU_SOURCE -D_XOPEN_SOURCE -std=c99 -ggdb -O0 main-test.c -L/usr/lib -lm -lglib-2.0 -o main-test
应用程序本身:
#include <stdio.h>
#include <ctype.h>
#include <alloca.h>
#include <glib.h>
#include <glib/gprintf.h>
#include "main.h"
const char *filter(char *original, pt_search_key key) {
const char *mname = "ModelName";
const char *pname = "Product";
const char *delim = " \t";
const char *delim_str = "\"";
const char *end = "\n";
char *value = NULL;
char *token;
char *copied = malloc(sizeof(original)+1);
strcpy(copied, original);
// Just delete initial tabs and whitespaces
while(isblank(*copied)) {
copied++;
continue;
}
token = strsep(&copied, delim);
if (!strcmp(token, mname))
{
token = strsep(&copied, delim_str);
if(!strcmp(token, "")) {
token = strsep(&copied, delim_str);
printf("[before] Token: %s\n", token);
printf("[before] Value: %s\n", value);
//*********** Strange behaviour is here!!! *****//
value = malloc(strlen(token)+1);
printf("[after] Token: %s\n", token);
printf("[after] Value: %s\n", value);
strcpy(value, token);
token = strsep(&copied, end);
while(*token != '\0') {
if(isblank(*token)) {
token++;
continue;
} else {
printf("String contains unexpected symbols:\n");
printf("%s\n", original);
exit(EXIT_FAILURE);
}
}
} else {
printf("String which contains %s is not correct", original);
exit(EXIT_FAILURE);
}
}
return value;
}
int main(int argc, char **argv)
{
filter(" ModelName \"Business Inkjet 1000\"\n", PT_MODELNAME);
return EXIT_SUCCESS;
}
此应用程序给出以下结果:
./main-test
[before] Token: Business Inkjet 1000
[before] Value: (null)
[after] Token: Business In!
[after] Value: 0
我完全误解了为什么token
已经改变了。对我来说,输出token
应该是:"Business Inkjet 1000"
. 错误在哪里?