0

My struct:

struct Company {
    string name;
    string profit_tax;
    string address;
};

I allocated by using line:

Company* a = (Company*)calloc(m, sizeof(Company));

with long long m =pow(10,9)+9 but pointer a is a null pointer after allocating. I don't know why this happened?. Please tell me solution, thanks!

9
  • In 99% of the time, the solution would be auto a = new Company[m]; Commented Jul 21, 2021 at 8:12
  • 4
    @StefanRiedel I disagree. Much better would be std::vector<Company> a(m);. Commented Jul 21, 2021 at 8:14
  • 2
    Size of std::string is something like 24 or 32 bytes on 64-bit architecture. Are you aware that you are allocating 72 or 96 GB? How much RAM do you have? Commented Jul 21, 2021 at 8:17
  • 1
    BTW, do you really want just to allocate memory (storage), or do you also want objects in this storage to be constructed? Commented Jul 21, 2021 at 8:19
  • @DanielLangr, I know it, my laptop has 8gb RAM. But this is task of my exercise. I think it is wrong Commented Jul 21, 2021 at 8:21

1 Answer 1

1

You're allocating way too much memory for your computer (unless you have a huge amount of memory).

See this godbolt example, the computation shows that on their hardware you would be trying to allocate 96GB of memory!

If this is an exercise, maybe you have a typo somewhere on the size you have to allocate? If not, you can try to replace the std::string to indexes/pointers to where the strings are stored. It should save some memory, but you'll still have issues. Otherwise you'll have to process the data differently, by processing it in chunks.

If you're using C++, why are you using calloc? You could simply have std::vector<company> companies(m); and that will allocate the memory AND construct all your objects. Less error-prone, and more readable.

Sign up to request clarification or add additional context in comments.

4 Comments

I am learing about hash, so the task requires create hash table with size as I mentioned. I used new, then i you calloc but both are not successfull.
All will fail if you can't allocate the memory you asked for.
link my exercise [link]drive.google.com/drive/recent
That link doesn't work. It would probably be better anyway that you modify your question with any relevant information you have.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.