我有與線建成之後(降低)簡單的應用:意外的結果
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"
。 錯誤在哪裏?
每串空終止在某些時候,通常結束;你也使用C字符串 –