2010-04-03 105 views
0

我有一個共享的結構,並且在其內部的請求結構:Ç嵌套結構指針問題

struct shared_data { 
    pthread_mutex_t th_mutex_queue; 

    struct request_queue { 
     int min; 
     int max; 
     char d_name[DIR_SIZE]; 
     pid_t pid; 
     int t_index; 
    } request_queue[BUFSIZE]; 

    int count; 

    int data_buffer_allocation[BUFSIZE]; 
    int data_buffers[BUFSIZE][100]; 
}; 

然後,我製備的請求;

struct shared_data *sdata_ptr; 
... 
... 
sdata_ptr->request_queue[index].pid = pid; 
strcpy(sdata_ptr->request_queue[index].d_name, dir_path_name); 
sdata_ptr->request_queue[index].min = min; 
sdata_ptr->request_queue[index].max = max; 

,編譯器警告我說,我做的strcpy函數不兼容的隱式聲明。我想這是指針的問題,但不是我上面寫的應該是真的?

+2

Did you include ? – 2010-04-03 11:28:53

+0

不,我現在做了,還沒有測試過,但我想現在就可以運行了。 – Halo 2010-04-03 14:19:35

回答

2

它似乎沒有嵌套結構的問題,至少沒有看到更多的代碼(即什麼是dir_path_name)。

這可能是一個遠射,但是您是否包含string.h以供編譯器查看strcpy的聲明?

+0

哇,我真的沒有。 – Halo 2010-04-03 14:09:34

3

「隱式聲明」警告通常意味着您沒有包含適當的頭文件,其中strcpy爲string.h。

而不是strcpy,您應該使用strlcpy,它允許您限制複製的字符數,防止緩衝區溢出。

1

暈,你可能會錯過包含string.h,因爲其他海報的說法。此外,如果dir_path_name大於d_name,則在該字段上執行的字符串複製操作將導致緩衝區溢出。

我出去肢體和建議你做到以下幾點:

  1. 明確檢查源緩衝區的大小小於或等於比目標(和bug的地獄,如果它是不是),
  2. 使用memcpy而不是海峽* CPY的
  3. 你memset的sdata_ptr-> request_queue [指數] .d_name的爲0,其餘(安全起見)

使用您的代碼示例,它會作爲foll行:

/* dir_path_name should be null-terminated for this to work */ 
size_t path_len = strlen(dir_path_name); 
char * dest = sdata_ptr->request_queue[index].d_name; 
size_t n = strlen(dest); 

if(path_len >= n) 
{ 
    ... err out, no workie 
} 

memcpy(dest, dir_path_name, n); 

if(path_len < n) 
{ 
    memset((dest+n),0,n-path_len); 
} 

希望它有幫助。

+0

謝謝,我可以認爲它不會超過250個字符。 – Halo 2010-04-03 14:10:25