簡體   English   中英

scanf c ++中的分段錯誤

[英]segmentation fault in a scanf c++

在我的程序中,有時會進行一次scanf(" %d %d", &num1, &num2); 而且我不斷收到SegmentationFault。 我不明白為什么。我的意思是,他們是int 我不確定是否應該為它們分配內存。 這是完整的代碼。

typedef struct my_type{
   int attr1;
   bool attr2;
} my_type;

int main (int argc, char * const argv[]) {

    int testCase, result, totalDom, numLines, num1, num2; 
    int aux_map_int = 0, linesScanned = 0;
    bool firstTime;
    scanf("%d\n %d %d", &testCase, &totalDom, &numLines);
    printf("totalDom: %d; numLines: %d\n", totalDom, numLines);

    std::map<int, std::vector<my_type> > my_map;

    while(aux_map_int < testCase+1){
        std::vector<my_type> my_vector;
        firstTime=true;

        while (linesScanned < numLines) {

            std::cin>>num_dom>>num_next_dom; /** SEGFAULT **/


            if(firstTime){
                my_vector[0].attr1 = num1;
                my_vector[0].attr2 = true;
                firstTime=false;
            }

            my_vector[num1].attr1 = num2;
            my_vector[num1].attr2 = false;

            linesScanned++;
        }
        aux_map_int++;
        my_map.insert(std::pair<int, std::vector<my_type> >(aux_map_int, my_vector));
    }
}

%d期望指向int的指針。 根據您自己的話,您正在傳遞指向雙打的指針。

更新:您的分段錯誤不是由於scanf引起的,而是因為您要在無限while循環內的向量中插入元素。 檢查aux_map_int是否正在增加:)

 std::cin>>num_dom>>num_next_dom; /** SEGFAULT **/

我假設該行應顯示為

 std::cin>>num1>>num2; /** SEGFAULT **/

如果是這樣,當您嘗試在內部while循環中插入my_vector時,將出現段錯誤:

        if(firstTime){
            my_vector[0].attr1 = num1;
            my_vector[0].attr2 = true;
            firstTime=false;
        }

        my_vector[num1].attr1 = num2;
        my_vector[num1].attr2 = false;

在此之前,您還沒有在向量中插入任何內容,而是試圖從中讀取內容。 這也是也會出現段錯誤的代碼

#include <vector>

typedef struct my_type{
   int attr1;
   bool attr2;
} my_type;

int main (int argc, char * const argv[]) 
{
    std::vector<my_type> v;
    v[0].attr1 = 1;
    v[0].attr1 = true;
}

修復上面的代碼,您將學習如何解決問題。 對不起,我不能給你答案:)

另外,您是否在std :: cin上使用scanf是否有特定原因? 如果答案是否定的,請改用此方法:

#include <iostream>
....
std::cin>>num1>>num2; 

它將沒有任何通常的scanf麻煩也可以正常工作。

如果必須使用scanf,請參考其文檔。 您的問題是您沒有使用正確的格式說明符。 我寧願您自己閱讀它,也不要僅僅告訴您它是什么。

從您發布的代碼看來,您使用scanf的原因是為了處理空白。 如果是這種情況,請使用std :: cin,並且您的空白問題已成為歷史。

正如@Tomek所說。 %d為int。 %f為float嘗試以下操作:

double num1, num2;
char str[128];
scanf("%f %f", &num1, &num2);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM