Doubling the Array Size in C?

So I have a this piece of C code:

void main (void){

int i,n,r,*pt1;
printf("Enter array size:\n");
scanf("%d",&n);
srand(time(NULL));
char niz[n];
pt1=niz;
for (i=0;i<n;i++){
    r=rand() % (15);
    printf("%d\n",r);
    if (r==0)
        break;
   niz[i]=r;
    if (i==n){
        pt1=(char*)realloc(niz,(sizeof(n)*2));
        if (pt1==NULL)
        printf("Jbg");
    }

}

free(pt1);
return 0;

}

Now the point here is when the counter comes to the end in the loop, to double the array size. Is the code with pt1 OK? Also, I'm getting segmentation fault at the end of the printf, and I'm not sure why. Thanks in advance!! :)

EDIT: Thanks to everyone for your answers, this is my revised & functional code:

void dupla(int n){ 

int i,r;
srand(time(NULL));
char * niz=malloc(n);
for (i=0;i<n;i++){
    r=rand() % (15);
    printf("%d\n",r);
        if (r==0)
            break;
niz[i]=r;
        if (i==n){
            niz=(char*)realloc(niz,n*2);
        }
}
if (niz==NULL)
            printf("Jbg");
        else
            printf("It works\n");
            printf("%d",sizeof(niz));
free(niz);
}


void main (void){

int n;
printf("Enter array size:\n");
scanf("%d",&n);
dupla(n);
return 0;
}
4

4 Answers

You must only use realloc on a pointer that was obtained by a call to malloc/calloc/realloc. Your code doesn't do that, so it is broken.

It should probably be like this:

char * niz = malloc(n);

// ...

char * tmp = realloc(niz, n * 2);

if (tmp) { niz = tmp; }
else     { /* flagrant error */ }

// ...

free(niz);
1

realloc says for its first parameter

Pointer to a memory block previously allocated with malloc, calloc or realloc, or a null pointer (to allocate a new block).

niz is on the stack so you will have undefined behaviour. You should allocate niz using malloc initially.

You can not realloc array allocated in stack. You should've started with allocating it in heap. Also, your initial array is char[] and pt1 is int*, which makes it a bit unclear what your intention is.

2
char* pt1 = malloc(n);
for (i=0; i < n + 1; i++) { // 1 more than the elements for the if.
    r = rand() % (15);
    printf("%d\n",r);
    if (r == 0)
        break;
    pt1[i] = r;
    if (i == n) { // Past end of array.
        n *= 2;
        --i; // So in the next loop i == old n.
        pt1 = (char*)realloc(pt1, n)); // n * sizeof(char)
        if (pt1 == NULL) {
            printf("Jbg");
            break;
        }
    }
}
free(pt1);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest