1

I have a programs like this,

Program 1

#include <stdio.h>
#include <string.h>

#define ARRAY_SIZE 0x320204

int main ()
{
    unsigned long long_array[ARRAY_SIZE];

    memset (long_array, 0, ARRAY_SIZE);

    return 0;
}

Program 2

#include <stdio.h>
#include <string.h>

#define ARRAY_SIZE 0x320204

int main ()
{
    unsigned long long_array[ARRAY_SIZE] = {0};

    //memset (long_array, 0, ARRAY_SIZE);

    return 0;
}

Both Programs are giving Segmentation Fault.

Please clarify how to initialize this long size array. Thanks in Advance.

Hakkim Ansari
  • 119
  • 3
  • 10

2 Answers2

4

The segmentation fault is because you try to allocate on the stack 0x320204 longs, which may be too much. In decimal, this is 3277316 * sizeof(unsigned long), which on my machine is 3277316 * 8 = 26218528 bytes, i.e. around 25 Mbytes.

The second way of initializing it is the most common, it will zero all elements. The first method will only zero the first ARRAY_SIZE bytes, but remember that sizeof(unsigned long) is usually 8 bytes, so you need to zero sizeof(unsigned long) * ARRAY_SIZE bytes.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
1

What you could do is use calloc, which is only one call, clearer to a lot of people, though not really a big deal, and uses the heap, which is the biggest benefit. Once you want to make really big array (or objects, or whatever), the heap is the place for you. Eventually, using the stack for this kind of stuff isn't practical, and will likely cause a stackoverflow error. Plus, you can pass this pointer returned from calloc to anything with having to worry what will happen to that memory allocated. This is unlike the stack, where it will probably be overwritten once that function returns, something that has happened to me plenty of times, creating bugs that are super hard to fix. There are downsides, however, to calloc like the fact that its pretty slow, but just as fast as memsetin this case. But if you don't really NEED all the bits to be set to 0, you could use malloc (much faster and more popular). The second downside to calloc or malloc is that you must call free on the pointers, otherwise you leak memory. Here's how to use calloc:

#include <stdlib.h> // or "#include <cstdlib>" in C++


/* Allocate space for array, set all bytes to 0,
   and return pointer. Then assign to long_array.
*/
unsigned long* long_array = (unsigned long*) calloc(ARRAY_SIZE);
// When you're done with this variable:
free(long_array);

Easy as that. Both calloc and malloc are made for this kind of stuff. I hope this helped!

Note: Though these links are to a C++ website, you can still use these functions in pure C by including <stdlib.h>

Jerfov2
  • 5,264
  • 5
  • 30
  • 52