2013-01-24 156 views
0

我有與線建成之後(降低)簡單的應用:意外的結果

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"錯誤在哪裏?

+0

每串空終止在某些時候,通常結束;你也使用C字符串 –

回答

3

我認爲這只是一個錯字,但sizeof(original)只是這種情況下指針的大小。

char *copied = malloc(sizeof(original)+1); ?? 

您需要:

char *copied = malloc(strlen(original)+1); 
+0

謝謝!我盯着這段代碼很長一段時間,無法找出哪裏出了什麼問題。這是我的錯誤。 – likern

+0

這是否意味着在我的情況下,我超出了分配內存的範圍(對於64位系統,'copied'是sizeof(original)+ 1 = 8 + 1個字節)並重寫其他一些內存?這就是爲什麼我得到這個奇怪的結果 - 在'malloc()'之後修改'token'? – likern

+0

對!再次調試並檢查新錯誤;-)祝你好運 – qPCR4vir