Segmentation fault - malloc-function

Hi guys. I'm quite new to c++ and i tried to take a given code to let a script run. Unfortunately the script is buggy and I found out, where the error is located.

I have a function that is called an stored in pValueStart. The result is always NULL (that's why 'error' is given out). If i uncomment the last line (memset), i get the sementation fault error - probably based on the result of NULL by 3 lines ago.

I debugged the values and can't see why I get NULL. Can you help me please?


Here the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <cstdlib>
#include "stdlib.h"
#include "memory.h"
#include "stdio.h"
#include "assert.h"
#include "string.h"

#define HashKeyNum (1<<20)
#define ValuePerBlock (1<<6)	
#define BlockNum 4				
using namespace std;

int main()
{
    size_t *pValueStart;
    
	pValueStart = (size_t*)malloc(sizeof(size_t) * HashKeyNum * ValuePerBlock * BlockNum);
    
    cout << HashKeyNum << endl;
    cout << ValuePerBlock << endl;
    cout << BlockNum << endl;
    cout << sizeof(size_t) * HashKeyNum * ValuePerBlock * BlockNum << endl;
    cout << pValueStart << endl;
    
	if (pValueStart==NULL)
		printf("error");
//	memset(pValueStart, 0, sizeof(size_t) * HashKeyNum * ValuePerBlock * BlockNum);
   
}


And that's what i get as output:
1
2
3
4
5
6
1048576
64
4
2147483648
0
error
Last edited on
You're requesting 2.1GB. That's more memory than your program has available.
malloc is returning null as evidenced by lines 26-27.

BTW, Lines 26-27 should be immediately after line 18 and should not proceed if null is returned.
Last edited on
Oh wow. Sounds reasonable. What's the max memory I can get from the program?
Depends on how much memory (RAM) + pagefile size (much slower!) your system has.

If you're compiling in 32-bit, chances are a continuous block of 2.1 GB might not be available (4 GB is max on 32-bit programs, unless you use some weird hacks that I don't know about).
You should (1) determine if you actually need 2.1 GB allocated at once, (2) perhaps split it up into multiple allocations, or (3) compile 64-bit so that you can use more memory address space.
Last edited on
It might be helpful of you describe what you are trying to do. HP built a full functioning scientific calculator in less than 1000 bytes of code. There's a good chance that your problem can be solved in a lot less than 2.1GB. :)
Thanks a lot :)
Well, facing the fact i didn‘t write the whole script on my own, i can‘t tell you in detail. But the song creates a big file (that‘s why it needs so much memory) with audio fingerprints of each song in my library. I guess an other way to handle this would be a sql database!?
Topic archived. No new replies allowed.