Increase the maximum size of char array

10.9k views Asked by At

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????

1

There are 1 answers

0
Pynchia On BEST ANSWER

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.