Home > Software engineering >  Confusion regarding a cast in C
Confusion regarding a cast in C

Time:12-31

I just wanted to ask what is the difference between

int *a = (int *)malloc(sizeof(int))

and

int *a = malloc(sizeof(int))

because I came across this situation while working on a project, and I tried to create an array as a pointer, and dynamically allocate memory to it. But when I was using int * a = malloc(sizeof(int)) I could not change any of the values of the array, causing a segmentation fault, and when I changed it to int * a =(int *)malloc(sizeof(int)) it all started working fine and dandy. To be more exact this is the code in question:

     int i = 0;
     for (i = 0; i < valCounter; i  ) {
          if (strcmp(vars[i].name, name) == 0) {
               return 2;
          }
     }
     strcpy(vars[valCounter].name, name);
     strcpy(vars[valCounter].type, type);
     i--;
     vars[i].intArrayVal = (int *)malloc((dimension   5) * sizeof(int)); 
     int j = 0;
     char currentNumber[1000];
     char elemente[1000];
     int *pointer;
     strcpy(elemente, elements);
     strcpy(currentNumber, strtok(elemente, ","));
     vars[i].intArrayVal[j  ] = atoi(currentNumber);
     while (currentNumber != NULL && j <= i) {
          strcpy(currentNumber, strtok(NULL, ","));
          vars[i].intArrayVal[j  ] = atoi(currentNumber);
     }
     valCounter  ;
     return 0;

Here if I was using the version without the cast it wasn't working properly, and after changing on the fact that I put the cast there it started working as intended.

CodePudding user response:

There is no difference in C language if you cast or not. If you get an error it means that you compile as C . C is a completely different language and do not use C compilers to compile C code

I could not change any of the values of the array, causing a segmentation fault

int *a = malloc(sizeof(int));

You allocate the space for one integer only - the array is only one element long. When you tried to access any element other than a[0] you were accessing the invalid memory location.

If you want to allocate space for more integers you need to:

int *a = malloc(NUMBER_OF_INTEGERS * sizeof(int));

or better

int *a = malloc(NUMBER_OF_INTEGERS * sizeof(*a));

Use objects in sizeofs instead of types. If you change the type of the object, you will not have to change all appearance of the sizeof. It is very easy to miss one or two introducing very hard to debug and find errors

  • Related