Dereferencing a null point when using malloc()?

Joined
Dec 26, 2024
Messages
1
Reaction score
0
Null pointer dereference error.png


Essentially, I am trying to use malloc here but the green line is letting me know I am dereferencing a null pointer here? It seems like a simple error but I don't understand why it is happening.

For context wall is a simple struct, that is a member of the PortalPanic class that looks like this:

class PortalPanic : public MinigameBase
{
public:
struct wall {
int xCord;
int yCord;
int width;
sf::Color color;
sf::RectangleShape wallRect;
};
.
.
.
more class stuff
 
Joined
Jun 12, 2020
Messages
60
Reaction score
3
I received assistance from generative AI to understand the issue I was facing with dereferencing a null pointer when using malloc to allocate memory for your wall structure. The AI explained that if malloc fails to allocate the requested memory, it returns a null pointer, and attempting to access any members of that null pointer leads to undefined behavior. It emphasized the importance of checking whether the pointer returned by malloc (or calloc) is nullptr before using it, which is a crucial step in preventing errors.
C++:
#include <iostream>
#include <cstdlib> // Pour malloc et free

class PortalPanic {
public:
    struct wall {
        int xCord;
        int yCord;
        int width;
        // Supposons que nous n'utilisons pas de couleur ou de forme ici pour simplifier
    };

    wall* createWall(int x, int y, int width) {
        // Allocation de mémoire pour un nouveau mur
        wall* newWall = (wall*)malloc(sizeof(wall));
        if (newWall == nullptr) {
            std::cerr << "Erreur d'allocation de mémoire pour wall." << std::endl;
            return nullptr; // Gestion de l'erreur
        }

        // Initialisation des membres de la structure
        newWall->xCord = x;
        newWall->yCord = y;
        newWall->width = width;

        return newWall; // Retourne le pointeur vers le nouveau mur
    }

    void destroyWall(wall* w) {
        if (w != nullptr) {
            free(w); // Libération de la mémoire
        }
    }
};

int main() {
    PortalPanic game;
    PortalPanic::wall* myWall = game.createWall(10, 20, 30);

    if (myWall != nullptr) {
        std::cout << "Mur créé avec succès : "
                  << "xCord = " << myWall->xCord
                  << ", yCord = " << myWall->yCord
                  << ", width = " << myWall->width << std::endl;

        // Libération de la mémoire
        game.destroyWall(myWall);
    }

    return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top