0

コードで STL マップを使用しています。関数の 1 つは、グローバルに宣言されている MAP を使用しており、セグメンテーション エラーが発生しています。しかし、そのMAPをローカル変数として作成すると、正常に機能します。次の関数作成の問題。

typedef map<int,string> DebugAllocPtrList_t;    
DebugAllocPtrList_t DebugAllocPtrList;    

int g_DebugAllocCount;


void DebugAllocNew(void *x, char *szFile, int iLine)
{        
    char szBuf[512];
    szBuf[0]=0; 
    sprintf(szBuf,"%s line %d", szFile, iLine);

    printf("Memory already allocated");

    DebugAllocPtrList[(int)x] = szBuf; //here it gives fault when declared globally.        
    g_DebugAllocCount++;    
}

この関数を独立して実行すると、機能しますが、この関数を実際のコードに入れると、セグメンテーション違反が 発生します。変数ローカルの場合も機能します。

4

1 に答える 1

3

I'd like to re-write your code to below code, no mixed C/C++ code, no global variables etc, more C++ way:

typedef map<int,string> DebugAllocPtrList_t;    

void incrementCount()
{
  static int g_DebugAllocCount = 0;
  g_DebugAllocCount++;
}

std::string makeString(const std::string& file, int line)
{
  std::stringstream ss;
  ss << file << " line " << line;
  return ss.str();
}

void DebugAllocNew(DebugAllocPtrList_t& ptr_map, int x, const std::string& file, int line)
{  
  std::cout <<"Memory already allocated" <<std::endl;
  ptr_map[x] = makeString(file, line);

  incrementCount();
}

int main()
{  
  DebugAllocPtrList_t t;

  DebugAllocNew(t, "something", 1, 2);
  DebugAllocNew(t, "something", 1, 2);
} 
于 2013-01-18T11:59:48.700 に答える