2

I was initializing array (unsigned short int) of size 100000000 in C 4.3.2 , and other two int array of size 1000000. But while submiting on Online judge, it was giving SIGSEGV error .

Therefor i decided to initialize my array dynamically with a default value 0, as adding value by loop takes much time.

My question is how to initialise array dynamically with a default value ?

2
  • 7
    100000000 really ? Commented Jul 27, 2013 at 14:15
  • at that size, it probably makes sense to request memory from the OS directly via mmap() for UNIX-like systems or VirtualAlloc() on Windows; conveniently, these functions already zero the memory for you... Commented Jul 27, 2013 at 14:58

2 Answers 2

9

You can use void *calloc(size_t nmemb, size_t size); function to initialize memory with 0,

The calloc() function allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is set to zero. If nmemb or size is 0, then calloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

 calloc(number of elements, sizeof(type));

or you can also use memset() explicitly to initialize memory allocated by malloc() call.

Note: calloc() isn't magic either - it will also use a loop somewhere to replace the garbage with all zeroes.

See also: Why malloc() + memset() is slower than calloc()?

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

9 Comments

+1 Probably it would be worth mentioning that calloc() isn't magic either - it will also use a loop somewhere to replace the garbage with all zeroes.
@Coffee_lover I am unemployed these days so I am getting time :P :D Thanks!
@GrijeshChauhan Now that is a reason! :D
@GrijeshChauhan; Yes. Your way to deal with pointer is easy to understand (and also different from others on SO). Keep it up.
@DavidRF ha ha...yes I like arcii arts, I have given a link of asciiflow in my profile....Thanks very much to all of you!
|
0

You can't eliminate the initialization time, no matter what you do. The best you can do is to attempt to optimize it. 2 techniques come to mind:

  • Efficiently use your HW. Use native size memory accesses to initialize the buffer. E.g., over 32-bit architecture loop and write in 4-byte chunks.
  • Unroll the loop to eliminate control overhead.

Unrolling will probably be applied anyway by optimizing compiler.

You can also try to move the initialization overhead to a non-critical section. E.g., you can use static variables that will be zero-initialized upon program start. Or, in contrast, you can delay the initialization till first use (lazy initialization).

Comments

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.