0

だから私は何日もメモリの問題に悩まされてきました。C++ で実行されているマルチスレッド プログラムがあります。double* ポインターを初期化します。私が読んだことと以前のプログラミング経験から、ポインターはガベージに初期化されます。0 に初期化した場合、またはプログラムに多すぎるメモリを割り当てた場合は Null になります。私の場合、割り当てなしでポインターを初期化すると、null ポインターが返されます。私が書いたパーサー関数は、解析された情報の配列へのポインターを返すと想定しています。関数を呼び出すと、

double* data;
data = Parser.ReadCoordinates(&storageFilename[0]);

ここで、配列への返されたポインターをデータに設定する必要があります。次に、配列から何かを出力しようとします。メモリ破損エラーが発生します。gdb を実行したところ、メモリ破損エラーが発生しました。

*** glibc detected *** /home/user/kinect/openni/Platform/Linux/Bin/x64-Debug/Sample-NiHandTracker: free(): corrupted unsorted chunks: 0x0000000001387f90 ***
*** glibc detected *** /home/user/kinect/openni/Platform/Linux/Bin/x64-Debug/Sample-NiHandTracker: malloc(): memory corruption: 0x0000000001392670 ***

誰かが私に何が起こっているのか説明できますか? ポインターをグローバルとして初期化しようとしましたが、それも機能しません。メモリを割り当てようとしましたが、それでもメモリ破損エラーが発生します。パーサーが動作します。簡単なプログラムでテストしました。そのため、他のプログラムで機能しない理由がわかりません。私は何を間違っていますか?必要に応じて、さらに情報を提供することもできます。

パーサー コード

double* csvParser::ReadCoordinates(char* ファイル名){

int x;              //counter
int size=0;         //
char* data;
int i = 0;          //counter

FILE *fp=fopen(filename, "r");


if (fp == NULL){
 perror ("Error opening file");
}

while  (( x = fgetc(fp)) != EOF ) {  //Returns the character currently pointed by the internal file position indicator
    size++;     //Number of characters in the csv file
}

rewind(fp);                         //Sets the position indicator to the beginning of the file
printf("size is %d.\n", size);      //print

data = new char[23];                //Each line is 23 bytes (characters) long
size = (size/23) * 2;               //number of x, y coordinates


coord = new double[size];           //allocate memory for an array of coordinates, need to be freed somewhere

num_coord = size;                   //num_coord is public

//fgets (data, size, fp);
//printf("data is %c.\n", *data);

for(x=0; x<size; x++){
    fgets (data, size, fp);
    coord[i] = atof(&data[0]);          //convert string to double
    coord[i+1] = atof(&data[11]);       //convert string to double
    i = i+2;
}


delete[] data;

fclose (fp);

return coord;

}

4

1 に答える 1

0

配列またはベクトルの範囲外に書き込むと、メモリの破損が発生します。
これは、ヒープ アンダーランおよびオーバーランと呼ばれます(どちら側にあるかによって異なります)。

ヒープの割り当てデータが破損するため、free() または new() 呼び出しで例外が発生するという症状が見られます。
メモリが割り当てられており、自分のものであるため、通常はアクセス違反は発生しませんが、ヒープのロジックによって使用されます。

配列の境界外に書き込んでいる可能性のある場所を見つけます。

于 2013-03-02T21:51:35.057 に答える