Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

malloc / new issue



  • Hi !
    Sorry for that, but as I am not a expert in programming, I am stucked here. :(

    I wanted to take avantage of new/delete instead of malloc/free.

    In an existing program, I had:

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

    and I changed for:

    int *bufferSize = new int();
    

    Compilation is OK but programm crashes when I try to access bufferSize. Can someone kindly tell me if something is wrong in my new line ? :(

    Thanks for your help / explanation


  • Lifetime Qt Champion

    First - where is the relation to Qt here?
    Second - why do you want to create a single integer on the heap at all?
    Third - you code does not show anything, especially not the place where it's crashing. Provide a minimal, compilable example so we can see what you're doing (wrong).



  • Also, in your first (old) line of code, you don't declare the type of bufferSize; is it a class member variable? In your second (new) line of code, you do declare the type, making it a local shadow variable (which should generate a compiler warning and/or c-tidy warning). If you try to reference bufferSize in another method, it would try to access the uninitialized member variable.



  • @Match0um where is this declared?
    int bufferSize;
    if declared as member variable during initialization use like this..
    bufferSize = new int(); //don't use int


Log in to reply