Ein*_*ing 5 c++ xcode pointers memory-management
我正在编写一个C++程序,它将数据输出到文件,生成python脚本并调用pyplot以进行绘图.
但是,当我按指针传递参数时,它可以正确编译,但无法运行.它返回错误.当我使用Xcode调试模式并逐步执行它时,它会偶然提供正确的结果,但并非总是如此.有时它也会返回错误.
我怀疑它可能是由一些内存分配问题引起的,但我无法确定究竟是什么问题.
我的代码如下:
1)主要
#include <iostream>
#include <stdlib.h>
#include <cmath>
#include "PyCPlot.h"
using namespace std;
double pi = 3.1415926;
int main(int argc, const char * argv[]) {
int nline = 100;
double * np_list = new double(nline);
double * pack_fraction_np = new double (nline);
for (int i=0; i<nline; i++){
np_list[i] = double(i)/double(nline)*2*pi;
pack_fraction_np[i] = cos(np_list[i]);
}
PyCPlot_data_fout("RandomPacking", nline, np_list, pack_fraction_np);
PyCPlot_pythonscript("RandomPacking", "Random Packing");
PyCPlot_pyplot("RandomPacking", "Random Packing");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
2)头文件
#ifndef PyCPlot_h
#define PyCPlot_h
#include <iostream>
#include <cmath>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
int PyCPlot_data_fout(string datafilename, int nline, double * x, double *y){
ofstream fout;
fout.open(datafilename+".txt");
fout << nline << endl;
for (int i=0; i<nline; i++){
fout << x[i] << " " << y[i] << endl;
}
fout.close();
return 0;
}
int PyCPlot_pythonscript(string datafilename, string plttitle){
string strhead = "import numpy as np\nimport matplotlib.pyplot as plt\n";
string strpltfig = "plt.figure()\n";
string strpltplt = "plt.plot(xlist, ylist)\n";
string strplttit = "plt.title('"+plttitle+"')\n";
string strpltshw = "plt.show()\n";
string strfileopen ="f = open('"+datafilename+".txt', 'r')\n";
string strreadline ="size = map(int, f.readline().split())\n";
string strpltlist ="xlist = np.zeros((size))\nylist = np.zeros((size))\n";
string strfor = "for i in range(size[0]):\n xlist[i], ylist[i] = map(float, f.readline().split())\n";
ofstream pyout;
pyout.open("PyCPlot_"+datafilename+".py");
pyout << strhead << strfileopen << strreadline << strpltlist << strfor;
pyout << strpltfig << strpltplt << strplttit << strpltshw;
pyout.close();
return 0;
}
int PyCPlot_pyplot(string datafilename, string plttitle){
string strsystemsh ="source ~/.bashrc; python PyCPlot_"+datafilename+".py";
system(strsystemsh.c_str());
return 0;
}
#endif /* PyCPlot_h */
Run Code Online (Sandbox Code Playgroud)
当它运行时,我得到以下错误消息
malloc: *** error for object 0x1002002e8: incorrect checksum for freed object - object was probably modified after being freed.
Run Code Online (Sandbox Code Playgroud)
您想要传递一个数组,因此传递一个可以在运行时调整大小的实际数组(std::vector),而不是一些希望指向数组第一个元素的随机指针(在本例中,它没有)
你的错误是使用new double(x)而不是new double[x]. 前者分配一个double值等于 的single x,后者分配一个doublesize 的数组x并返回指向第一个元素的指针,但是,正如我所说,如果您实际使用的话,根本不会遇到这个问题std::vector并且不像 90 年代早期那样涉足指针(更不用说,如果使用的话就不会出现内存泄漏std::vector)。