2017-02-12 37 views
0

與指針播放:分段故障與strtol將

char a[]=" 0xa this is a343 good"; 
char* *endptr=NULL; 
long int b=0; 
b=strtol(a,endptr,0); 
b=strtol(*endptr,endptr,0); 

爲什麼我得到段錯誤的最後一行? *endptrchar *還是? 如果我很好理解strtol的行爲,它在此讀取第一個整數10,然後*endptr將指向0xa之後的下一個空格。我對嗎 ?

+2

你不能解引用指針爲NULL,你這樣做:'* endptr'。 – ForceBru

+0

@BLUEPIXY我知道,但爲什麼它不適用於上面的代碼? – Sabrina

+3

@Sabrina'* endptr'與'* NULL'相同,它給你一個分段錯誤。 – 4386427

回答

1

你崩潰無關與strtol 。問題是您取消引用具有值NULL的指針。這是非法的,並導致崩潰(seg故障)。

你的問題是在這裏:

b=strtol(*endptr,endptr,0); 
     ^^^^^^^ 
     Dereference a NULL leads to a crash 

你的問題是一樣的,因爲這代碼:

char** endptr=NULL; 
char* p = *endptr; // Crash!! 

所以你的問題真有無關strtol

關於strtol

如果你想strtol更新*endptr,你需要傳遞一個值,該值NULL

做到這一點的方式,是使char*變量(注:一個char**),並通過的*地址**這char*strtol

像:

char a[]=" 0xa this is a343 good"; 
char* p; // Notice: just one * as you need a pointer to char 
long int b=0; 
b=strtol(a, &p,0); 
      ^^ 
      Notice: & (aka address of). So you pass the address of 
        a pointer to char. Equivalent to char** as expected 
        by strtol 
+0

爲什麼要在第一個strtol之後更新endtpr爲NULL? – Sabrina

+0

@Sabrina - 它不會被第一次調用更新。只是因爲它是'NULL',所以'strtol'不會碰它 – 4386427

0

在你的程序中endptr = NULL,一個 所以這行會拋出異常: b = strtol(* endptr,endptr,0);

望着函數的定義: http://www.cplusplus.com/reference/cstdlib/strtol/

,則不應使用雙重指針:

嘗試是這樣的:

char a[] = " 0xa this is a343 good"; 
char* endptr = NULL; 
long int b = 0; 
b = strtol(a, &endptr, 16); 
b = strtol(endptr, &endptr, 16); 
+4

C沒有例外...... segfault是標準認爲「未定義行爲」的一個例子。 – StoryTeller

+0

Visual C++將其稱爲例外,但從技術上講,您是正確的 –

+0

答案在哪裏? – Sabrina