Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

long integer as array index in C gives segmentation fault

The following C Code gives a segmentation fault:

#include <stdio.h>
#include <stdint.h>

int main(){
        uint32_t *a;
        uint32_t idx=1233245613;
        a[idx]=1233;
        return 0;
}

How can I use uint32_t as index of an array in C? Or how can I use array like structure which can get uint32_t and 12 digit numbers as an index?

I'd appreciate any kind of help.

like image 580
systemsfault Avatar asked Dec 04 '22 16:12

systemsfault


1 Answers

  • The variable "a" is just a pointer varaible.
  • A pointer variable holds the address of a memory location.
  • You need to point a to a memory location that has the space you need already allocated.

Also you are trying to index pretty far in the array. You may not have enough memory available for this so be sure to check for NULL.

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

int main(void){

        uint32_t *a;
        uint32_t idx=1233245613;

        //This allows you to index from 0 to 1233245613
        // don't try to index past that number
        a = malloc((idx+1) * sizeof *a);
        if(a == NULL)
        {
           printf("not enough memory");
           return 1;
        }


        a[idx]=1233;
        free(a);
        return 0;
}
like image 189
Brian R. Bondy Avatar answered Mar 15 '23 12:03

Brian R. Bondy