2012-12-14 53 views
1

我试着写一个幂到一个文件,但我得到一个堆损坏,如果我的出发阵列比大小6大,和IM不知道为什么。它适用于任何大小的数组6或以下。不能解决这个问题。获取堆损坏时写入到文件

另外,test.txt的是我在数组中读出。如果该文件包含“1,2,3,4,5,6”它工作正常,但它包含“1,2,3,4,5,6,7”我得到堆腐败。

#include <stdio.h> 
#include <stdlib.h> 
#include <string> 
#include <iostream> 
#include <fstream> 
#include <sstream> 
#include <algorithm> 
#include "N26.h" 
#include <math.h> 

using namespace std; 

void increaseArray(int* theArray, int size) 
{ 
    int i = size; 
    int n = i+1; 
    int* newArray = new int[n]; 

    for(int cnt=0;cnt<n;cnt++) 
    { 
     newArray[cnt] = theArray[cnt]; 
    } 

    newArray[n-1]= NULL; 
    theArray = newArray; 

    return; 
} 

void printPowerSet(int *s, int n) 
{ 
    int i=0,j=0; 
    ofstream myFile; 
    double SetSize=pow(2.0,n); 

    myFile.open("powerset1.txt", std::ios_base::app); 

    cout<<"{size of original}"<< n <<endl; 
    cout<<"{number of sets}"<< SetSize-1 <<endl; 

    for(i=1;i<SetSize;++i) 
    { 
     for(j=0;j<n;++j) 
     { 
      if(((i>>j)&1)==1) 
      {   
       myFile << s[j] <<","; 
      } 
     } 

     myFile<<endl; 
    } 

    return; 
} 

int main() 
{ 
    ifstream myFile; 
    int item; 
    string input =""; 

    string fileName = "test.txt"; 

    myFile.open(fileName); 
    while(myFile) 
    { 
     int k = 1; 
     int* transaction= new int[1]; 

     if(!getline(myFile,input)) 
      break; 

     istringstream ss(input); 
     while(ss) 
     { 
      if(!getline(ss,input, ',')) 
       break; 

      input.erase(remove_if(input.begin(), input.end(), isspace), input.end()); 
      item = atoi(input.c_str()); 
      transaction[k-1] = item; 
      increaseArray(transaction,k); 

      k++; 
     } 

     for(int i =0; i<k-1;i++) 
     { 
      cout << transaction[i]; 
     } 
     printPowerSet(transaction, k-1); 
      cout << endl; 
     transaction=NULL; 
} 

    system("Pause"); 
    return 0; 
} 

回答

2

您的increaseArray()函数不起作用,因为您只是更改指针的本地副本。你必须传递一个双指针或一个指针引用来做你想做的事。到指针的引用的

实施例: 空隙increaseArray(INT * & theArray,INT大小)

相反,我建议使用std::vector,因为这将自动增长。

我怀疑这对你的问题有任何影响,但我没有看到你曾经删除,要么。你正在泄漏记忆。在重新指定新分配指针之前,请删除旧分配:

delete [] theArray; // The "[]" is important! 
theArray = newArray; 
+0

谢谢,我的工作对我的increaseArray()函数。我不允许使用STL :( – user1898442

+0

啊,谢谢我认为它的工作! 当我呼吁increaseArray,我用increaseArray(*&交易,K) 现在的参数是无效increaseArray(int *&theArray,int size) 这就是你的意思是否正确? – user1898442

+0

是的,但看到我的约内存泄漏编辑和尼古拉的回答。 –

1

除了Fred的回答。

看看这是怎么回事里面increaseArray(),特别是这些行:

int i = size; 
int n = i+1; 
int* newArray = new int[n]; 

for(int cnt=0;cnt<n;cnt++) 
{ 
    newArray[cnt] = theArray[cnt]; 
} 

你分配size + 1元素的数组,然后遍历原始。这是一个接一个的过程,即您正在访问原始数组之外的一个元素。 可能根据new如何设置堆,但可以确定是undefined behavior,可以为您提供分段错误。

+0

哦,谢谢!好抓,我完全忽略了。 – user1898442