2016-02-29 46 views
0

這是一個簡單的程序,應該從一個字符串創建一個子字符串,然後它應該返回子字符串作爲可以打印出來的東西。 這實際上是一個練習,只有子字符串函數可以改變。問題是我找不到不會引發各種警告和錯誤的返回類型。返回參數不起作用 - 給我奇怪的錯誤

我應該如何更改返回類型?

static void panic(const char *serror) 
{ 
    printf("%s", serror); 
    exit(1); 
} 

static void *xmalloc(size_t size) 
{ 
    void *ptr; 
    if (size == 0) 
     panic("Size is 0!\n"); 
    ptr = malloc(size); 
    if (!ptr) 
     panic("No mem left!\n"); 
    return ptr; 
} 

static char *substring(const char *str, off_t pos, size_t len) 
{ 
    char out [len]; 
    int index; 

    for(index = 0; index < (pos + len); index++) 
    { 
     if(index >= pos && index < (pos + len)) 
     { 
     out[index - pos] = str[index]; 
     } 
    } 

    return out; 
} 

int main(int argc, char **argv) 
{ 
    char *foo = "Nicht\n"; 
    char *bar = substring(foo, 2, 3); 
    printf("%s", bar); 
    free(bar); 
    return 0; 
} 
+0

注意,錯誤消息應被打印到'stderr',而不是標準輸出。然而,像panic()這樣的函數是你的工具包中的一個好工具。 –

回答

1

您可以通過

  • 解引用指針bar一個指向已經消失了局部變量調用2 取消定義的行爲
  • 通過一個非NULL指針,該指針不指向通過malloc()calloc()realloc()分配的緩衝區。

還要注意的是

  • 您通過添加空字符來終止字符串。
  • 您的環路效率不高。

校正代碼:

static char *substring(const char *str, off_t pos, size_t len) 
{ 
    char *out = xmalloc(len + 1); 
    int index; 

    for(index = pos; index < (pos + len); index++) 
    { 
     out[index - pos] = str[index]; 
    } 
    out[len] = '\0'; 

    return out; 
} 
+0

是的,這會停止錯誤,但它仍然不會打印任何內容。 – Mattia

+0

@Chris此代碼確實打印了一些東西。 https://ideone.com/OUf0BM – MikeCAT