2012-11-13 55 views
0

我不斷收到大小爲1的無效讀取的valgrind錯誤,我無法確定原因。大小爲1的讀取無效Strcpy

什麼是導致錯誤?

==24647== Invalid read of size 1 
==24647== at 0x40258EA: strcpy (mc_replace_strmem.c:437) 
==24647== by 0x8048606: main (source.c:26) 
==24647== Address 0x0 is not stack'd, malloc'd or (recently) free'd 
==24647== 
==24647== 
==24647== Process terminating with default action of signal 11 (SIGSEGV) 
==24647== Access not within mapped region at address 0x0 
==24647== at 0x40258EA: strcpy (mc_replace_strmem.c:437) 
==24647== by 0x8048606: main (source.c:26) 
==24647== If you believe this happened as a result of a stack 
==24647== overflow in your program's main thread (unlikely but 
==24647== possible), you can try to increase the size of the 
==24647== main thread stack using the --main-stacksize= flag. 
==24647== The main thread stack size used in this run was 16777216. 

這裏是我的代碼如下,並且我在檢測到錯誤的行(source.c:26)中註釋了這一行。

#include <stdio.h> 
#include <stdlib.h> 
#include <limits.h> 
#include <string.h> 

int main() 
{ 

    char input[100]; 

    char name[100]; 

    char age[100]; 

    int agee[100]; 

    fgets(input,sizeof(input),stdin); //i scan in the string and store int char array called input. 

    char *charpoint;//declare pointer character 

    charpoint=strtok(input,"\"");//run strtoken with quotation marks as second part of argument. 

    strcpy(name,charpoint); 

    char * charpoint2=strtok(NULL,"\","); 

    strcpy(age,charpoint2); //This line is where the error occurs. line 26 

    sscanf(age,"%d",&agee[0]); 

    printf("%s %d",name, agee[0]); 

    system("pause"); 

    return 0; 

} 
+1

什麼是該程序的輸入? – Raam

+0

「John,Smith」,55 – user1819801

+0

輸出應該是John,Smith 55 – user1819801

回答

7

從手冊頁(重點煤礦):

的的strtok()和strtok_r()函數返回一個指針到串中的每個隨後的令牌的開始 ,替換令牌之後本身 與NUL字符。 當不再有令牌時,返回空指針 。

從你的錯誤

==24647== Address 0x0 is not stack'd, malloc'd or (recently) free'd 

所以你的指針charpoint2爲NULL,這意味着你以前strtok調用沒有找到你所期望的。您應該檢查這種可能性並輸入有關輸入格式的錯誤。當然,您應該確認您的strtok通話符合您的要求。

0

有關您的程序的幾件事。

  1. 在使用前清除所有數組,這將確保沒有垃圾被讀入。您可以通過使用memset或只是字符輸入[100] = {0};
  2. 讀入數據後,通過明確設置輸入[99] ='\ 0'確保輸入爲空終止。這是爲了確保輸入永遠不會超出數組的大小
  3. 對strtok返回的指針執行空檢查,但不能保證您得到您期望的結果。適當處理空值。我的直覺是,charpoint2對你來說是空的,因此也是錯誤。
相關問題