So I have a file I wanna put its content in an array and that needs malloc or new. I do that on a large project, it was working fine but i guess some changes were made to this project and now that malloc causes a crash and "char* array = new char[20000]" causes the same crash. On my test project and it works fine. Can someone tell me how to fix this.
I am still new to c++.

Thanks in advance.

I can't post all the source code, its big, but here is the function that causes the crash

void *safe_malloc(size_t size) {
	void* ret;
	ret = malloc(size); //crashes here
	if (ret != NULL) {
		return ret;
	} else {
		printf("safe_malloc");
		exit(1);
    }
}
uint8_t *load_file(uint8_t *path, uint32_t *size_buf){
	FILE *fp;
	uint32_t result;
	uint8_t *data;
	uint32_t size;
	fopen_s(&fp, (const char *)path, "rb");
	if(fp != NULL){
		fseek(fp, 0, SEEK_END);
		size = ftell(fp);
		rewind(fp);
		data = (uint8_t*)safe_malloc(size);
		result = fread(data, 1, size, fp);
		fclose(fp);
		if(result != size){
			free(data);
			if(size_buf != NULL) *size_buf = 0;
			return NULL;
		}else{
			if(size_buf != NULL) *size_buf = size;
			return data;
		}
	}
	else
		printf("can't open file");
	if(size_buf != NULL) *size_buf = 0;
	return NULL;
}

I couldn't do no debugging either cuz now project is made with cmake and I don't know how to make it to produce .pdb files.

Edited 6 Years Ago by tehmarto: n/a

If malloc() is crashing instead of returning NULL then you have a memory overrun somewhere else in the code which is messing with the malloc runtime table. You might need to retrace your steps and figure out where the memory overlaps are occurring. I don't see anything wrong with your code up to the crash point.

Yep I removed load_file and it was crashing on the next malloc. So yes it ain't the load_file function that makes the crash it was some sprint_f before it that corrupts the memory I think. Anyway I fixed it. Thanks

This question has already been answered. Start a new discussion instead.