Search code examples
c++cpointerscompiler-errorsstructure

Access to field results in dereference of a null pointer in C


This question is related to C Programming Language: I get error: Access to field 'x' results in a dereference of null pointer

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

typedef struct A {  
    int *x;  
    int *y;  
} A;  

void allocateStruct(int sizeN, A *aType);
void printInfo(A *aType);
  
int main() {   
    A *genericA;  
    allocateStruct(5, genericA);  
    int x[5] = {2, 3, 4, 5, 6};  
    int y[5] = {12, 36, 40, 52, 23};   

    genericA->x = x;  
    genericA->y = y;  
    printInfo(genericA);   
}  

void allocateStruct(int sizeN, A* aType) {  
    aType->x = (int*)malloc(sizeN * sizeof(int));   
    aType->y = (int*)malloc(sizeN * sizeof(int));    
}  
 
void printInfo(A *aType) { 
    printf("%i %i\n",  aType->x[0], aType->y[0] ); 
} 

Solution

  • You haven't allocated a memory to the structure and yet you are accessing it's member in

    void allocateStruct(int sizeN, A* aType) {
        aType->x = (int*)malloc(sizeN * sizeof(int));   
        aType->y = (int*)malloc(sizeN * sizeof(int));    
    }
    

    allocate memory to the structure itself first

    atype = malloc(sizeof(A))
    

    You need to return the address of atype to your main function as you are passing the pointer by value else your changes in allocateStruct wont be accessible in main and also cause a memory leak. You don't need to pass atype as a parameter in case you are returning the address.

    A* allocateStruct(int sizeN){
        A* atype;
        atype = malloc(sizeof(A));
        aType->x = malloc(sizeN * sizeof(int));   
        aType->y = malloc(sizeN * sizeof(int)); 
        return atype;
    }
    

    and in main

    atype = allocateStruct(5);
    

    Also you dont need to typecast explicitly in C, the malloc returns a void pointer and it can be assigned to any type. And also for completeness so that you dont cause memory leaks at the end of main just free all your memory that you have malloced.

    free(atype->x);
    free(atype->y);
    free(atype);