Hi,

I have the following C++ code

#include <string>
#include <iostream>

//maybe std::string
using namespace std;

int main() {
	size_t r = 134480;
	size_t c = 268960;
	
	size_t **opt;
	opt = (size_t **)malloc(r * sizeof(size_t *));
	if(opt != NULL) {
		opt[0] = (size_t *)malloc(r * c * sizeof(size_t));
		if(opt[0] != NULL) {
			for (int i = 1; i < c; i++) {
				opt[i] = opt[0] + i * c;
			}
		} else {
cout << "line:189:r:" << r << endl;
cout << "line:190:c:" << c << endl;
cout << "ERR:diff:185:Memory allocation failed." << endl;
		}
	} else {
cout << "ERR:diff:183:Memory allocation failed." << endl;
	}
        
        ..... free code ....
}

I am compiling it on CentOs using the command

g++ test.cpp -o test

When I run it I get the following error:

line:189:r:134480
line:190:c:268960
ERR:diff:185:Memory allocation failed.

Can someone explain me why my first c++ code is failing?

Maybe 36169740800 * sizeof(size_t) is too much?

Maybe 36169740800 * sizeof(size_t) is too much?

Thanks for your reply, how can I check that I am within the limit of my machine?

ok you must be right .. with 2 bytes per int that's like 34 GB .. way more than I can afford .. thanks.

I don't quite see why you're doing this they way you are. Typically, a dynamic 2D array is done like this.

I don't quite see why you're doing this they way you are. Typically, a dynamic 2D array is done like this.

yes initially i did like array1 then I wanted to try array2 to make sure that the code was not the culprit.

commented: Ha! Jeez I'm off these days. I point to the page and don't even recognize the idiom contained where I'm pointing. :icon_razz: +14

malloc ?? this is not c++, maybe plain c
--> new

34 GB ?? 2 bytes just allow 2,1 GB to be addressed by

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.