2015-10-29 39 views
0

這是幾個小時了,我真的很沮喪,爲什麼會發生這種事情,所以我問是否有任何好的靈魂可以解釋這一點給我。兩個不同的輸出使用malloc

int main() 
{ 
    FILE* filePointer; 
    int* tempPointer1; 
    int* tempPointer2; 

    filePointer = fopen("numbers.txt","r"); 

    tempPointer1 = (int*) malloc(sizeof(int)*10); 
    tempPointer2 = tempPointer1; 

    int j; 
    for(j=0;j<10;j++) 
    { 
     fscanf(filePointer,"%d ",tempPointer1); 
     printf("%d ", *tempPointer1); 
     tempPointer1+=sizeof(int); 
    } 

    printf("\n"); 

    int i; 
    for(i=0;i<10;i++) 
    { 
     printf("%d ", *tempPointer2); 
     tempPointer2+=sizeof(int); 
    } 

    fclose(filePointer); 
    return 0; 
} 

這是即時得到輸出:

1 2 3 4 5 6 7 8 9 10 

1 2 3 12337 5 6 7 8 9 10 

任何人都可以解釋,爲什麼?

P.S如果我使用靜態int數組輸出是相同的。

+0

[不投射的malloc的結果](http://stackoverflow.com/a/605858/1413133) –

回答

4

指針算術的設計使得增量具有類型指針的大小。所以在這個部分

tempPointer1+=sizeof(int); 

你是太大的一步遞增,超越了數組的邊界和調用未定義的行爲。您需要通過1遞增,即

tempPointer += 1; 

,或者更簡潔,

++tempPointer1; 

注意:你不應該在C.投malloc結果您可以將其分配給非空指針直接:

tempPointer1 = malloc(sizeof(int)*10); 
+0

啊,感謝FO答案是,但是,如果我試圖寫入我沒有分配的內存,那麼在這種情況下我不會得到分段錯誤嗎? –

+0

@SirDrinksCoffeeALot你得到未定義的行爲。有時候這可能會導致分段錯誤,但不一定。 – juanchopanza

+0

@SirDrinksCoffee ALot段錯誤只發生在您訪問您無權訪問的細分受衆羣時。段通常是1KB或甚至64KB或更大(取決於底層操作系統如何使用MMU)的範圍內存塊,因此在離開有效段之前可以覆蓋相當遠的距離。幾乎總是將0附近的塊標記爲無權訪問(所以NULL解除引用會導致錯誤),但除此之外,操作系統會將其標記爲不可訪問或不可訪問。 (IOW,不要依靠段錯誤來找到你的錯誤) –

相關問題