Thread: Need Help

  1. #1
    Registered User
    Join Date
    Oct 2019
    Posts
    43

    Need Help

    Hi Everyone, I am Shafiul Islam. I am beginer in C and C++. Recently I wrote a piece of code on Template and Malloc(). But I am afraid about the hidden bug. It works file till now for a small matrix and vector though. I want to keep this code as more accurate. If any expat can have a look on my code and give me some recommendation if there is any hidden bug inside of my code.

    Code:
        #include <stdlib.h>
        #include <typeinfo>
        #include <cstring>
        #include<iostream>
    
    
        template <class type1, class type2>
        void allocateData1DbyMalloc(type1** data1D, type2 nRow) {
            int size = (char*) &(*data1D)[1] - (char*) & (*data1D)[0];
        *data1D = (type1*)malloc(nRow * size); // sizeof(type1));
        } 
    
    
        template <class type1>
        void deAllocateData1DbyFree(type1** data1D) {
        free(*data1D);
        }
    
    
        template <class type1, class type2>
        void allocateData2DbyMalloc(type1*** data2D, type2 nRow,           type2     nColumn) {
        int size = (char*) & (*data2D)[1] - (char*) & (*data2D)[0];
        *data2D = (type1 * *)malloc(size * nRow); // sizeof(type1*)
        if (*data2D) {
            size = (char*) & (**data2D)[1] - (char*) & (**data2D)  [0];
        for (int i = 0; i < nRow; i++) {
                    (*data2D)[i] = (type1*)malloc(size * nColumn); // sizeof(type1)
            }
        }
    }
    
    
        template <class type1, class type2>
        void destroyMatrix2DbyFree(type1*** data2D, type2      numberOfRow) {
        for (int row = 0; row < numberOfRow - 1; row++)
            free((*data2D)[row]);
        free(*data2D);
        }
    
    
    int main() {
        int n = 4;
    //    std::cin >> n;
        double* constrainVector;
        allocateData1DbyMalloc(&constrainVector, n);
        constrainVector[0] = 16.0;
        constrainVector[1] = 25.6;
        constrainVector[2] = -11.2;
        constrainVector[3] = 12.7;
        for (int i = 0; i < n; i++)
            std::cout << i << "    " << constrainVector[i] << std::endl;
        deAllocateData1DbyFree(&constrainVector);
    
    
        double** matrix2D;
        allocateData2DbyMalloc(&matrix2D, n, n);
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                matrix2D[i][j] = (double)(i+j);
    
    
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
            {
                std::cout << i << j << "    " << matrix2D[i][j] << std::endl;
            }
        destroyMatrix2DbyFree(&matrix2D, n);
    
    
        return 0;
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Moved to the C++ programming forum.

    Don't use malloc. Use containers, or if these aren't applicable, use smart pointers.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Oct 2019
    Posts
    43
    Nope. I prefer to use malloc() due to algorithmic performance. No recommendation for the vector container please!.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    That should only be chosen when you have measured and found that containers are a bottleneck for your use cases. Since you are a beginner, this means you should default to containers first.

    If you insist on malloc, then you should be aware that your code will not work correctly on class types with non-trivial constructors unless you change your code to also use placement new. If you don't know what's this, then you're not ready to say "No recommendation for the vector container please!" as it means you don't know enough C++ yet. Use containers.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > int size = (char*) &(*data1D)[1] - (char*) & (*data1D)[0];
    This is a truly AWFUL way of doing sizeof.

    > Nope. I prefer to use malloc() due to algorithmic performance. No recommendation for the vector container please!.
    You came for advice, and then you reject it.

    Is there any actual point in continuing to offer help?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    Oct 2019
    Posts
    43
    Hi Salem, don't get me wrong please. I mean, I don't want to change the track from this specific point, specially at this moment. I already spend a significant amount of time behind this. There might a lot of modern tools off course. But for now, I want to put attention on this specific point. Why do you think "This is a truly AWFUL way of doing sizeof"?.

  7. #7
    Registered User
    Join Date
    Oct 2019
    Posts
    43
    Hi Laserlight, don't get me wrong please. I mean, I don't want to change the track from this specific point, specially at this moment. I already spend a significant amount of time behind this. There might a lot of modern tools off course. But for now, I want to put attention on this specific point.

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    It is better to spend even more time to learn modern tools since they will form your toolbox for programming in C++.

    Consider what you'll have to do if you insist on malloc:
    • Check that malloc does not return a null pointer, and if it does you'll need to handle it, including manually destroying already constructed objects.
    • Use placement new to invoke constructor.
    • Explicitly invoke the destructor.


    Quote Originally Posted by Shafiul
    Why do you think "This is a truly AWFUL way of doing sizeof"?.
    Because you might as well use sizeof as it communicates intent better by being direct.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User
    Join Date
    Oct 2019
    Posts
    43
    Hi Laserlight, Thanks for your suggestion. I prefer to keep this code as a C standard as much a possible, not C++. Specially the memory management part.

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Err... then why are you using templates?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    Oct 2019
    Posts
    43
    Hmm good question. Templates is not responsible for memory allocation but malloc is. This malloc can be replaced by cudamalloc() in future for computing. That's the reason, why I used malloc().

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    How do you intend to deal with class types with non-trivial constructors?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Registered User
    Join Date
    Oct 2019
    Posts
    43
    Well, my plan is to put the top part of my code from line 7 to 38 in a header file and afterwards, add this header file in the .cpp file.

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    That's irrelevant to my question: I'm talking about correctly invoking constructors. For something like using cudamalloc(), the right approach is to define an allocator that is then used with a container.

    EDIT: oh sorry, I'm mistaken about your header and cpp file approach not working. You're talking about the entire function template, so you're doing what's normal, so it should work. It still doesn't handle the issue of class types with constructors that have to be invoked though.
    Last edited by laserlight; 10-27-2019 at 09:09 AM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Registered User
    Join Date
    Oct 2019
    Posts
    43
    Hi Laserlight, well, i don't know the answer of "I'm talking about correctly invoking constructors" because I don't get the question honestly. Can you explain your question a bit please if possible. Then i will try to do my best to answer it. Well, the idea is GPU system need a memory mapping between cudamalloc and malloc to transfer the data from CPU to GPU. Based on the memory mapping, sometimes I need to call realloc() to optimise the memory mapping between CPU and GPU.

Popular pages Recent additions subscribe to a feed

Tags for this Thread