2

I have written some code in C by taking the maximum size of char array as 100. It worked well. But when I increase the maximum size of char array to 10000 it gives me segmentation fault(as it has exceeded its limit). Can someone tell me how can I increase the maximum size and store a string of length 10000.

i.e How can I take the "char a[100]" as "char a[10000]" and execute the same code????

Sowmya
  • 151
  • 1
  • 1
  • 8
  • 5
    There is no *maximum* size, there's only the reserved size. You seem to be making a mistake. Please post a complete, minimal example, and please make sure to format all source code as source code (`{}` button over input field). – Marcus Müller Jun 07 '15 at 17:53
  • 2
    Post the code which is used to operate on `array` **a** so that it will be more clear to resolve the issue – Amol Saindane Jun 07 '15 at 18:11
  • 1
    It's unusual for a modern machine to have a problem with an array of 10k. And seg fault is usually not the right error for an allocation limit problem. You probably have a bug that happens to be exposed by making the array bigger. – Gene Jun 07 '15 at 18:28

1 Answers1

8

You can allocate the array dynamically:

#include <stdlib.h>
char *a = malloc(100*sizeof(char));
if (a == NULL)
{
 // error handling
 printf("The allocation of array a has failed");
 exit(-1);
}

and when you want to increase its size:

tmp_a = realloc(a, 10000*sizeof(char));
if ( tmp_a == NULL ) // realloc has failed
{
 // error handling
 printf("The re-allocation of array a has failed");
 free(a);
 exit(-2);
}
else //realloc was successful
{
 a = tmp_a;
}

Eventually, remember to free the allocated memory, when the array is not needed anymore:

free(a);

Basically realloc(prt, size) returns a pointer to a new memory block that has the size specified by size and deallocates the block pointed to by ptr. If it fails, the original memory block is not deallocated. Please read here and here for further info.

Pynchia
  • 10,996
  • 5
  • 34
  • 43