Search code examples
c++windowsvisual-studiofreetype

Freetype Exception thrown: read access violation. face was nullptr


''' FT_Face face = nullptr;;

FT_GlyphSlot g = face->glyph;
FT_Library ft;
if (FT_Init_FreeType(&ft))
    std::cout << "ERROR::FREETYPE: Could not init FreeType Library" <<
    std::endl;

if (FT_New_Face(ft, "fonts/arial.ttf", 0, &face))
    std::cout << "ERROR::FREETYPE: Failed to load font" << std::endl;
FT_Set_Pixel_Sizes(face, 0, 48);
if (FT_Load_Char(face, 'X', FT_LOAD_RENDER))
    std::cout << "ERROR::FREETYTPE: Failed to load Glyph" << std::en '''

When I compile the program, I get this error. "Unhandled exception thrown: read access violation.face was nullptr."


Solution

  • The problem(mentioned error) is that somewhere in your program you're dereferencing face when it is nullptr which leads to undefined behavior.

    To solve this add a check to see if face is nullptr or not before dereferencing it as shown below:

    //go inside the if block only if face is not nullptr
    if(face !=nullptr)
    {
        //you can safely dereference face here
    }
    //otherwise print a message to the console
    else 
    {
        //at this point face is nullptr so don't dereference it at this point
        std::cout<<"cannot dereference face "<<std::endl;
        
    }
    

    Additionally make sure(if not already) that face is initialized i.e., it points to an object of appropriate type.