new/delete 메모리 에러
글쓴이: yeonjooo / 작성시간: 토, 2016/03/19 - 2:07오전
#include <iostream>
#include <string>
using namespace std;
double *P;
int *N;
int *K;
double **dp;
int M;
double getLowestP(int, int);
int main() {
int count = 0;
while (!cin.eof()) {
P = new double[23];
P[0] = 0;
N = new int[23];
N[0] = 0; N[1] = 1;
K = new int[101];
count++;
cin >> P[1];
P[1] = floor(P[1] * 100) / 100;
cin >> M;
for (int i = 2; i < M + 2; i++) {
cin >> N[i];
cin >> P[i];
P[i] = floor(P[i] * 100) / 100;
}
/*문자열 읽어와 정수만 추출하여 K 배열 채우기*/
int i = 0;
string input_k;
getline(cin, input_k);
if(input_k.compare(""))
getline(cin, input_k);
while (input_k[i] == ' ')
i++;
if(i!=0)
input_k = input_k.substr(0, i-1);
i = 0;
int position = input_k.find(" ");
while (position != -1) {
K[i] = atoi(input_k.substr(0, position).c_str());
input_k = input_k.substr(position + 1);
i++;
position = input_k.find(" ");
}
if (position == -1 && !input_k.empty())
K[i] = atoi(input_k.substr(0, position).c_str());
cout << "Case " << count << " : " << endl;
for (int h = 0; h < M; h++) {
/*dp 배열 초기화*/
dp = new double*[M + 2];
for (i = 0; i < M + 2; i++) {
dp[i] = new double[K[h] + 1];
for (int j = 0; j < K[h] + 1; j++)
dp[i][j] = 0;
}
double result = getLowestP(M + 1, K[h]);
cout << "Buy " << K[h] << " for $" << result << endl;
for (i = 0; i < M + 2; i++)
delete []dp[i];
delete []dp;
}
delete []P;
delete []N;
delete []K;//////////////////////에러 발생 부분
}
}
/*재귀 함수*/
double getLowestP(int i, int j) {
if ((i <= 0) || (j <= 0))
return 0;
if (dp[i][j] != 0)
return dp[i][j];
else {
int temp1 = getLowestP(i, j - N[i]) + P[i];
int temp2 = getLowestP(i - 1, j);
if (temp2 == 0)
dp[i][j] = temp1;
else {
if (temp1 < temp2)
dp[i][j] = temp1;
else
dp[i][j] = temp2;
}
return dp[i][j];
}
}안녕하세요. new/delete로 인한 메모리 문제가 발생하여 이렇게 질문드립니다. 발생한 에러는 std::bad_array_new_length 에러입니다.
배열을 잘못 사용한 것 같은데, 아무리 찾아봐도 그 이유를 잘 모르겠습니다. 각 배열의 크기는 입력값의 최대 범위로 잡았고, 실제 test case들의 경우 대부분 원래 크기의 절반도 사용하지 않았습니다.
Forums:


로직을 잘못 짜서 배열 크기를 음수로 했네요ㅠㅠ.
로직을 잘못 짜서 배열 크기를 음수로 했네요ㅠㅠ. 해결했습니다. 감사합니다.
댓글 달기