<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Gründe für malloc NULL zu returnen]]></title><description><![CDATA[<p>Hi Leute,<br />
einen schönen guten Tag erstmal <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f642.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--slightly_smiling_face"
      title=":)"
      alt="🙂"
    /> ich schreibe gerade eine Matrizen-Klasse(ich weiß, C++), jedoch macht mir malloc() Probleme. Undzwar(wie schreibt man das? ^^) allociere ich in einer for()-Schleife mehrmals ein double Array. Das ist auch so weit gut und schön, funktioniert auch. Wenn der Schleifen-Durchlauf nun zuende ist(-&gt;auch der Destruktor der Klasse in der es erstellt wird wird aufgerufen) und das ganze von neuem beginnt, gibt malloc() aber plötzlich beim Allocieren des Speicherns für eine temporäre Matrix NULL zrück. Und das obewohl ich über 12 Gigabyte RAM frei habe und das Programm auch nur 45 MB verbraucht <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f615.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--confused_face"
      title=":confused:"
      alt="😕"
    /> <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f62e.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--face_with_open_mouth"
      title=":open_mouth:"
      alt="😮"
    /> so weit ich das nachvollziehen kann wird mein Speicher auch immer schön über den Destruktor gefreet, daran dürfte es also auch nicht liegen <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f615.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--confused_face"
      title=":/"
      alt="😕"
    /> fällt euch vielleicht aus dem Stegreif ein Grund dafür ein? Wenn nicht arbeite ich halt mit new und delete :p aber der Grund würde mich auch mal interessieren <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f603.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--grinning_face_with_big_eyes"
      title=":D"
      alt="😃"
    /><br />
MfG<br />
DragonRaider</p>
]]></description><link>https://www.c-plusplus.net/forum/topic/326803/gründe-für-malloc-null-zu-returnen</link><generator>RSS for Node</generator><lastBuildDate>Sun, 31 May 2026 00:58:51 GMT</lastBuildDate><atom:link href="https://www.c-plusplus.net/forum/topic/326803.rss" rel="self" type="application/rss+xml"/><pubDate>Tue, 08 Jul 2014 10:26:16 GMT</pubDate><ttl>60</ttl><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 10:42:11 GMT]]></title><description><![CDATA[<p>Hi Leute,<br />
einen schönen guten Tag erstmal <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f642.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--slightly_smiling_face"
      title=":)"
      alt="🙂"
    /> ich schreibe gerade eine Matrizen-Klasse(ich weiß, C++), jedoch macht mir malloc() Probleme. Undzwar(wie schreibt man das? ^^) allociere ich in einer for()-Schleife mehrmals ein double Array. Das ist auch so weit gut und schön, funktioniert auch. Wenn der Schleifen-Durchlauf nun zuende ist(-&gt;auch der Destruktor der Klasse in der es erstellt wird wird aufgerufen) und das ganze von neuem beginnt, gibt malloc() aber plötzlich beim Allocieren des Speicherns für eine temporäre Matrix NULL zrück. Und das obewohl ich über 12 Gigabyte RAM frei habe und das Programm auch nur 45 MB verbraucht <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f615.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--confused_face"
      title=":confused:"
      alt="😕"
    /> <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f62e.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--face_with_open_mouth"
      title=":open_mouth:"
      alt="😮"
    /> so weit ich das nachvollziehen kann wird mein Speicher auch immer schön über den Destruktor gefreet, daran dürfte es also auch nicht liegen <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f615.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--confused_face"
      title=":/"
      alt="😕"
    /> fällt euch vielleicht aus dem Stegreif ein Grund dafür ein? Wenn nicht arbeite ich halt mit new und delete :p aber der Grund würde mich auch mal interessieren <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f603.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--grinning_face_with_big_eyes"
      title=":D"
      alt="😃"
    /><br />
MfG<br />
DragonRaider</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407540</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407540</guid><dc:creator><![CDATA[DragonRaider]]></dc:creator><pubDate>Tue, 08 Jul 2014 10:42:11 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 10:42:18 GMT]]></title><description><![CDATA[<p>Zeig mal Code.</p>
<p>Wieso verwendest du überhaupt malloc/free in C++?</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407546</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407546</guid><dc:creator><![CDATA[Singender Holzkübel]]></dc:creator><pubDate>Tue, 08 Jul 2014 10:42:18 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 10:43:34 GMT]]></title><description><![CDATA[<p>DragonRaider schrieb:</p>
<blockquote>
<p>Hi Leute,<br />
einen schönen guten Tag erstmal <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f642.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--slightly_smiling_face"
      title=":)"
      alt="🙂"
    /> ich schreibe gerade eine Matrizen-Klasse(ich weiß, C++), jedoch macht mir malloc() Probleme.</p>
</blockquote>
<p>-&gt;Using C++<br />
-&gt;Using malloc</p>
<p>[] Du hast den Sinn von <code>new</code> und <code>delete</code> verstanden.</p>
<p>DragonRaider schrieb:</p>
<blockquote>
<p>Undzwar(wie schreibt man das? ^^) allociere ich in einer for()-Schleife mehrmals ein double Array. Das ist auch so weit gut und schön, funktionier auch.</p>
</blockquote>
<p>&quot;alloziieren&quot; ist der Infinitiv.<br />
Und hoffentlich machst du auch schön <code>free/delete</code> , sonst leakst du Speicher.</p>
<p>DragonRaider schrieb:</p>
<blockquote>
<p>Wenn der Schleifen-Durchlauf nun zuende ist(-&gt;auch der Destruktor der Klasse in der es erstellt wird wird aufgerufen) und das ganze von neuem beginnt, gibt malloc() aber plötzlich beim Allocieren des Speicherns für eine temporäre Matrix NULL zrück. Und das obewohl ich über 12 Gigabyte RAM frei habe und das Programm auch nur 45 MB verbraucht</p>
</blockquote>
<p><code>malloc</code> kann fehlschlagen, wenn du ordentlich viel Speicher oder 0 Bytes Speicher anforderst. Auch, wenn der Speicher arg fragmentiert ist (Billigbetriebssysteme wie Windows (;)) sind davon häufiger betroffen) oder du zwar Speicher reserviert hast, dieser aber nicht zu physikalischem Speicher gemappt wird (über MMU), kann <code>malloc</code> fehlschlagen. Mal vor dem Call ausgeben, was du für Parameter übergibst, ist die Basis jedes Debuggings.</p>
<p><code>new</code> und <code>delete</code> werden da vermutlich die gleichen Probleme wie <code>malloc</code> und <code>free</code> aufweisen.</p>
<p>Da du keinen Quellcode angegeben hast, ist das alles Spekulation.<br />
Aber für den Fall, dass du das hier machst:</p>
<pre><code>while(solange_icke_lustisch_bin)
{
        mein_typ*mein_var=malloc(viele_viele_bunte_bytes);
        /*Mach voll geheime Sachen*/
        mein_var.~mein_typ();
}
</code></pre>
<p>Dann lass dir gesagt sein, dass der explizite Aufruf des Destruktors NICHT den Speicher freigibt, den du mit <code>malloc</code> geholt hast. Der Destruktor kümmert sich nur um den Speicher, der im Klassenobjekt alloziiert wird - und der Standarddestruktor auch nur dann, wenn die Objekte auf dem Stack liegen. Für alles andere musst du noch mal <code>free</code> aufrufen.</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407547</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407547</guid><dc:creator><![CDATA[speicheritis]]></dc:creator><pubDate>Tue, 08 Jul 2014 10:43:34 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 10:44:35 GMT]]></title><description><![CDATA[<p>Keine Ahnung <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f603.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--grinning_face_with_big_eyes"
      title=":D"
      alt="😃"
    /> ich nehme jetzt wohl einfach new und delete und fertig ist es. Ihr müsst euch echt nicht meine ganze Klasse antun xD trotzdem danke <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f44d.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--thumbs_up"
      title=":+1:"
      alt="👍"
    /></p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407548</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407548</guid><dc:creator><![CDATA[DragonRaider]]></dc:creator><pubDate>Tue, 08 Jul 2014 10:44:35 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 10:55:40 GMT]]></title><description><![CDATA[<p>Und nein so mache ich es nicht ^^ Jetzt einfach mal meine auf Konstruktor und Destruktor minimierte Klasse und die sehr stark minimierten Aufrufe:</p>
<pre><code>#ifndef MATRIX_LIBRARY_H
#define MATRIX_LIBRARY_H

#include &lt;opencv2/core/core.hpp&gt;
#include &lt;opencv2/highgui/highgui.hpp&gt;
#include &lt;opencv2/imgproc/imgproc.hpp&gt;

class Matrix
{
public:
    Matrix(unsigned const int m, unsigned const int n);                //m = rows, n = columns
    ~Matrix();

    unsigned const int getN();
    unsigned const int getM();

    Matrix operator*(Matrix b);
    double *operator[](unsigned const int i);
    Matrix&amp; operator=(Matrix other);

    void print();

private:
    unsigned int _n, _m;
    double *_data;
};

#endif
</code></pre>
<pre><code>#include &quot;mat.h&quot;
#include &lt;stdexcept&gt;
#include &lt;cstdlib&gt;
#include &lt;cstring&gt;
#include &lt;iostream&gt;

Matrix::Matrix(unsigned const int m, unsigned const int n) : _n(n), _m(m)
{
    _data = (double*)malloc(sizeof(double) * _m * _n);
    if(_data == NULL)
    {
        std::cerr &lt;&lt; &quot;_data == NULL&quot; &lt;&lt; std::endl;
        throw std::bad_alloc();
    }
    memset(_data, 0, sizeof(double) * _m * _n);
}

Matrix::~Matrix()
{
    free(_data);
}
</code></pre>
<pre><code>(Alles mögliche includieren)
while(true)
{
    Matrix A(1, 5);
}
</code></pre>
<p>Ich kann auch gerne den gesamten Quellcode senden, aber ich will es jetzt mal nicht übertreiben... Ihr habt ja auch besseres zu tun <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f603.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--grinning_face_with_big_eyes"
      title=":D"
      alt="😃"
    /><br />
MfG<br />
DragonRaider</p>
<p>Edit: Und ja ich weiß, es gäbe da auch noch cv::Mat <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f644.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--face_with_rolling_eyes"
      title=":rolling_eyes:"
      alt="🙄"
    /></p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407550</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407550</guid><dc:creator><![CDATA[DragonRaider]]></dc:creator><pubDate>Tue, 08 Jul 2014 10:55:40 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 11:14:34 GMT]]></title><description><![CDATA[<p>Ich denke nicht, dass in den geposteten Schnippseln der Grund für das NULL sichtbar ist.</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407556</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407556</guid><dc:creator><![CDATA[oenone]]></dc:creator><pubDate>Tue, 08 Jul 2014 11:14:34 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 11:53:21 GMT]]></title><description><![CDATA[<p>DragonRaider schrieb:</p>
<blockquote>
<p>Und nein so mache ich es nicht ^^</p>
</blockquote>
<p>Und wieso nutzt du nicht new/delete?<br />
Sie haben nur Vorteile gegenüber malloc. Sie beachten Konstruktoren und Destruktoren, es gibt die Möglichkeit callbacks im Fehlerfall zu installieren und du kannst sie überschreiben für effizientere Allokation o. ä.<br />
Sie werden zwar höchstwahrscheinlich nicht dein Problem lösen (du kriegst dann eine Exception anstatt NULL), sind aber ansonsten besser.</p>
<p>Der beste Weg ist aber, rohe dynamische Allokation ganz zu vermeiden. In diesem Fall bietet sich std::vector an, dann hast du auch keinen Stress wegen dem fehlenden Kopierkonstruktor.</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407563</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407563</guid><dc:creator><![CDATA[Nathan]]></dc:creator><pubDate>Tue, 08 Jul 2014 11:53:21 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 11:59:16 GMT]]></title><description><![CDATA[<p>Wie <em>oenone</em> sehe ich jetzt in diesem &quot;Beispiel&quot; auch nicht den Grund für Deine Probleme.</p>
<p>Allerdings frage ich mich, warum Du so einen eigensinnigen Stil entwickeln willst. <code>malloc()</code> / <code>free()</code> , die ganzen <code>const</code> in der Schnittstelle...</p>
<p>Das mit dem <code>memset()</code> macht übrigens nur, das was Du willst, wenn die Repräsentation von 0.0 als double auch nur aus lauter 0 Bytes besteht (Was aber zu Deinem Glück bei IEEE754 der Fall ist - jedenfalls +0.0)</p>
<p>Wo ist denn da eigentlich der Kopierkonstruktor? Und wie hast Du den Zuweisungsoperator implementiert?</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407567</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407567</guid><dc:creator><![CDATA[Furble Wurble]]></dc:creator><pubDate>Tue, 08 Jul 2014 11:59:16 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 12:16:08 GMT]]></title><description><![CDATA[<p>Hallo,<br />
OK, danke. Dann werde ich mal meinen Sourcecode senden... Es wäre sehr nett, würde sich jemand das ganze mal ansehen. Danke schon mal im Voraus <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f642.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--slightly_smiling_face"
      title=":)"
      alt="🙂"
    /></p>
<p>mat.h:</p>
<pre><code>#ifndef MATRIX_LIBRARY_H
#define MATRIX_LIBRARY_H

#include &lt;opencv2/core/core.hpp&gt;                //Das kann eigentlich auch raus, ist noch Altlast
#include &lt;opencv2/highgui/highgui.hpp&gt;
#include &lt;opencv2/imgproc/imgproc.hpp&gt;

class Matrix
{
public:
    Matrix(unsigned const int m, unsigned const int n);                //m = rows, n = columns
    ~Matrix();

    unsigned const int getN();
    unsigned const int getM();

    Matrix operator*(Matrix b);
    double *operator[](unsigned const int i);
    Matrix&amp; operator=(Matrix other);

    void print();

private:
    unsigned int _n, _m;
    double *_data;
};

#endif
</code></pre>
<p>mat.cpp:</p>
<pre><code>#include &quot;mat.h&quot;
#include &lt;stdexcept&gt;
#include &lt;cstdlib&gt;
#include &lt;cstring&gt;
#include &lt;iostream&gt;

Matrix::Matrix(unsigned const int m, unsigned const int n) : _n(n), _m(m)
{
    std::cout &lt;&lt; &quot;    Entered Matrix::Matrix(unsigned const int m, unsigned const int n)&quot; &lt;&lt; std::endl;
    _data = new double[_m * _n];
    std::cout &lt;&lt; &quot;    Allocated double* _data&quot; &lt;&lt; std::endl;
    memset(_data, 0, sizeof(double) * _m * _n);
    std::cout &lt;&lt; &quot;    Set values to 0&quot; &lt;&lt; std::endl;
}

Matrix::~Matrix()
{
    //free(_data);
    delete [] _data;
}

unsigned const int Matrix::getN()
{
    return _n;
}

unsigned const int Matrix::getM()
{
    return _m;
}

Matrix&amp; Matrix::operator=(Matrix other)
{
    if(this != &amp;other)
    {
        double *tmp_data = new double[other.getM() * other.getN()];
        std::cout &lt;&lt; &quot;    Allocated double* tmp_data&quot; &lt;&lt; std::endl;
        if(tmp_data == NULL)
        {
            std::cerr &lt;&lt; &quot;tmp_data == NULL&quot; &lt;&lt; std::endl;
            throw std::bad_alloc();
        }

        for(unsigned int i = 0; i &lt; other.getM(); ++i)
        {
            for(unsigned int j = 0; j &lt; other.getN(); ++j)
            {
                tmp_data[i * other.getN() + j] = *other[i * other.getN() + j];
            }
        }
        std::cout &lt;&lt; &quot;    Updated double* tmp_data&quot; &lt;&lt; std::endl;

        _m = other.getM();
        _n = other.getN();
        std::cout &lt;&lt; &quot;    Updated double _m and double _n&quot; &lt;&lt; std::endl;

        delete [] _data;
        std::cout &lt;&lt; &quot;    Freeed double* _data&quot; &lt;&lt; std::endl;
        _data = tmp_data;
        std::cout &lt;&lt; &quot;    Updated double* _data&quot; &lt;&lt; std::endl;
    }

    return *this;
}

double *Matrix::operator[](unsigned const int i)
{
    return &amp;_data[i * _n];
}

Matrix Matrix::operator*(Matrix b)
{
    std::cout &lt;&lt; &quot;  Entered Matrix Matrix::operator*(Matrix b)&quot; &lt;&lt; std::endl;
    Matrix result(this-&gt;getM(), b.getN());
    std::cout &lt;&lt; &quot;  Created Matrix result&quot; &lt;&lt; std::endl;

    if(this-&gt;getN() != b.getM())
    {
        std::cerr &lt;&lt; &quot;Invalid Matrix size.&quot; &lt;&lt; std::endl;
        throw std::logic_error(&quot;Invalid Matrix size.&quot;);
    }
    std::cout &lt;&lt; &quot;  Checked size of Input Matrize&quot; &lt;&lt; std::endl;

    for(unsigned int i = 0; i &lt; this-&gt;getM(); ++i)
    {
        for(unsigned int j = 0; j &lt; b.getN(); ++j)
        {
            double value = 0.0;
            for(unsigned int index = 0; index &lt; b.getM(); ++index)
            {
                value += (*this)[i][index] * b[index][j];
            }
            result[i][j] = value;
        }
    }

    std::cout &lt;&lt; &quot;  Returning Matrix result&quot; &lt;&lt; std::endl;
    return result;
}

void Matrix::print()
{
    for(unsigned int i = 0; i &lt; _m; ++i)
    {
        for(unsigned int j = 0; j &lt; _n; ++j)
        {
            std::cout &lt;&lt; (*this)[i][j];
            if(j &lt; _n - 1)
            {
                std::cout &lt;&lt; &quot; | &quot;;
            }
        }
        std::cout &lt;&lt; std::endl;
    }
}
</code></pre>
<p>main.cpp:</p>
<pre><code>#include &quot;mat.h&quot;
#include &lt;exception&gt;
#include &lt;iostream&gt;
#include &lt;string&gt;
#include &lt;time.h&gt;
#include &lt;opencv2/core/core.hpp&gt;
#include &lt;opencv2/highgui/highgui.hpp&gt;
#include &lt;opencv2/imgproc/imgproc.hpp&gt;
using namespace cv;

#define DEBUG
#define DEBUG2

std::string paths[9] =  {&quot;D:\\Matrix\\Pictures\\05.jpg&quot;,
                         &quot;D:\\Matrix\\Pictures\\11.jpg&quot;,
                         &quot;D:\\Matrix\\Pictures\\03.jpg&quot;,
                         &quot;D:\\Matrix\\Pictures\\04.jpg&quot;,
                         &quot;D:\\Matrix\\Pictures\\02.jpg&quot;,
                         &quot;D:\\Matrix\\Pictures\\06.jpg&quot;,
                         &quot;D:\\Matrix\\Pictures\\07.jpg&quot;,
                         &quot;D:\\Matrix\\Pictures\\08.jpg&quot;,
                         &quot;D:\\Matrix\\Pictures\\10.jpg&quot;};

double dRand(double dMin, double dMax)
{
    double d = (double)rand() / RAND_MAX;
    return dMin + d * (dMax - dMin);
}

int main()
{
    srand(time(NULL));

    Matrix A(35 * 3, 15 * 3);
    Matrix B(15 * 3, 1);
    Matrix C(35 * 3, 1);

    Matrix ReferenceValue(35 * 3, 1);

    for(unsigned int i = 0; i &lt; 35 * 3; ++i)
    {
        for(unsigned int j = 0; j &lt; 15 * 3; ++j)
        {
            A[i][j] = dRand(0.0, 0.02);
        }
    }

    namedWindow(&quot;Full Size Image&quot;, WINDOW_AUTOSIZE);

    namedWindow(&quot;Original Image Section&quot;, WINDOW_NORMAL);
    resizeWindow(&quot;Original Image Section&quot;, 7 * 50, 5 * 50);

    namedWindow(&quot;Downscaled Image Section&quot;, WINDOW_NORMAL);
    resizeWindow(&quot;Downscaled Image Section&quot;, 5 * 50, 3 * 50);

    namedWindow(&quot;Output&quot;, WINDOW_NORMAL);
    resizeWindow(&quot;Output&quot;, 7 * 50, 5 * 50);

    for(unsigned int index = 0; index &lt; 9; ++index)
    {
        Mat image = imread(paths[index], CV_LOAD_IMAGE_COLOR);
        imshow(&quot;Full Size Image&quot;, image);

        Mat ToScaleDown(5, 7, image.type());

        std::cout &lt;&lt; &quot;Rows: &quot; &lt;&lt; image.rows &lt;&lt; &quot;, Cols: &quot; &lt;&lt; image.cols &lt;&lt; std::endl;

        for(unsigned int x = 0; x &lt; image.cols - 7; ++x)
        {
            for(unsigned int y = 0; y &lt; image.rows - 5; ++y)
            {
                for(unsigned int xSection = 0; xSection &lt; 7; ++xSection)
                {
                    for(unsigned int ySection = 0; ySection &lt; 5; ++ySection)
                        {
                        //Updaten der ReferenceValue Matrix
                        }
                }

                std::cout &lt;&lt; &quot;Updated Matrix ReferenceValue&quot; &lt;&lt; std::endl;

                ToScaleDown = image(Range(y, y + 5), Range(x, x + 7));
                std::cout &lt;&lt; &quot;Loaded cv::Mat ToScaleDown&quot; &lt;&lt; std::endl;
                imshow(&quot;Original Image Section&quot;, ToScaleDown);
                resize(ToScaleDown, ToScaleDown, cvSize(5, 3), 0, 0, INTER_AREA);
                std::cout &lt;&lt; &quot;Resized cv::Mat ToScaleDown&quot; &lt;&lt; std::endl;
                imshow(&quot;Downscaled Image Section&quot;, ToScaleDown);

                for(unsigned int i = 0; i &lt; 3; ++i)
                {
                    for(unsigned int j = 0; j &lt; 5; ++j)
                    {
                        //Updaten der Matrix B
                    }
                }
                std::cout &lt;&lt; &quot;Updated Matrix B&quot; &lt;&lt; std::endl;

                C = A * B;
                std::cout &lt;&lt; &quot;Calculated Matrix C&quot; &lt;&lt; std::endl;

                Mat OutputMat(5, 7, image.type());
                for(unsigned int i = 0; i &lt; 5; ++i)
                {
                    for(unsigned int j = 0; j &lt; 7; ++j)
                    {
                        //Matrix C -&gt; cv::Mat OutputMat
                    }
                }
                std::cout &lt;&lt; &quot;Generated cv::Mat OutputMat&quot; &lt;&lt; std::endl;
                imshow(&quot;Output&quot;, OutputMat);

                for(unsigned int i = 0; i &lt; 35 * 3; ++i)
                {
                    //Bearbeiten der Matrix A
                }
                std::cout &lt;&lt; &quot;Matrix A Re-Calculated&quot; &lt;&lt; std::endl;
                std::cout &lt;&lt; std::endl;
                cvWaitKey();
            }
            std::cout &lt;&lt; &quot;One Column - &quot; &lt;&lt; x &lt;&lt; std::endl;
        }
    }
}
</code></pre>
<p>Das Log bist zum Absturz sieht dann wie folgt aus:</p>
<pre><code>Entered Matrix::Matrix(unsigned const int m, unsigned const int n)
    Allocated double* _data
    Set values to 0
    Entered Matrix::Matrix(unsigned const int m, unsigned const int n)
    Allocated double* _data
    Set values to 0
    Entered Matrix::Matrix(unsigned const int m, unsigned const int n)
    Allocated double* _data
    Set values to 0
    Entered Matrix::Matrix(unsigned const int m, unsigned const int n)
    Allocated double* _data
    Set values to 0
    Entered Matrix::Matrix(unsigned const int m, unsigned const int n)
    Allocated double* _data
    Set values to 0
Rows: 747, Cols: 1023
Updated Matrix ReferenceValue
Loaded cv::Mat ToScaleDown
Resized cv::Mat ToScaleDown
Updated Matrix B
  Entered Matrix Matrix::operator*(Matrix b)
    Entered Matrix::Matrix(unsigned const int m, unsigned const int n)
    Allocated double* _data
    Set values to 0
  Created Matrix result
  Checked size of Input Matrize                     //Schlechtes Englisch ^^
  Returning Matrix result
    Allocated double* tmp_data
    Updated double* tmp_data
    Updated double _m and double _n
    Freeed double* _data
    Updated double* _data
Calculated Matrix C
Generated cv::Mat OutputMat
Matrix A Re-Calculated

Updated Matrix ReferenceValue
Loaded cv::Mat ToScaleDown
Resized cv::Mat ToScaleDown
Updated Matrix B
  Entered Matrix Matrix::operator*(Matrix b)
    Entered Matrix::Matrix(unsigned const int m, unsigned const int n)
</code></pre>
<p>MfG DragonRaider</p>
<p>Edit 1: Ich hatte mal gelesen, es wäre sauberer sich Argumente als const übergeben zu lassen, wenn man sie in der Funktion nicht verändern möchte<br />
Edit 2: Danke, das mit memset hatte sich mir beim Lesen der Referenz auch schon erschlossen. Aber ich war einfach mal davon ausgegangen, dass man 0 halt mit nur Nullen &quot;darstellt&quot;<br />
Edit 3: Hahaha in der main.cpp fehlte ein Stück ^^</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407568</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407568</guid><dc:creator><![CDATA[DragonRaider]]></dc:creator><pubDate>Tue, 08 Jul 2014 12:16:08 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 13:41:34 GMT]]></title><description><![CDATA[<p>Das ganze brauche ich mir gar nicht ansehen.<br />
Der fehlende Kopierkonstruktor ist schon mal ein schöner showstopper.</p>
<p>Sobald Du eine Kopie anfertigst (z.b. das Argument von <code>Matrix&amp; operator=(Matrix);</code> ), fliegt Dir das doch alles um die Ohren.</p>
<p>Schau Dir nochmal Referenzen als Typen von Funktionsargumenten an. Also &quot;by value&quot; vs. &quot;by reference&quot;.</p>
<p>Lies mal, was man unter der <em>Rule of Three</em> in C++ versteht und warum Dich das betrifft.</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407589</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407589</guid><dc:creator><![CDATA[Furble Wurble]]></dc:creator><pubDate>Tue, 08 Jul 2014 13:41:34 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 15:38:05 GMT]]></title><description><![CDATA[<p>Vielen Dank <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f642.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--slightly_smiling_face"
      title=":)"
      alt="🙂"
    /> ich habe mir den Artikel zur Rule of Three noch ein mal durch gelesen und daraufhin den Copykonstruktor und, soweit mir das logisch vor kam noch ein mal die const neu gesetzt. Jetzt sieht meine Klasse wie folgt aus:</p>
<p>mat.h:</p>
<pre><code>#ifndef MATRIX_LIBRARY_H
#define MATRIX_LIBRARY_H

class Matrix
{
public:
    Matrix(unsigned int m, unsigned int n);                //m = rows, n = columns
    Matrix(const Matrix &amp;other);
    ~Matrix();

    unsigned int getN() const;
    unsigned int getM() const;

    Matrix operator*(const Matrix b) const;
    double *operator[](unsigned const int&amp; i) const;
    Matrix&amp; operator=(Matrix other);

    void print();

private:
    unsigned int _n, _m;
    double *_data;
};

#endif
</code></pre>
<p>mat.cpp</p>
<pre><code>#include &quot;mat.h&quot;
#include &lt;stdexcept&gt;
#include &lt;cstdlib&gt;
#include &lt;cstring&gt;
#include &lt;iostream&gt;

Matrix::Matrix(unsigned int m, unsigned int n) : _n(n), _m(m)
{
    _data = new double[_m * _n];
    memset(_data, 0, sizeof(double) * _m * _n);
}

Matrix::Matrix(const Matrix&amp; other)
{
    double *tmp_data = new double[other.getM() * other.getN()];

    for(unsigned int i = 0; i &lt; other.getM(); ++i)
    {
        for(unsigned int j = 0; j &lt; other.getN(); ++j)
        {
            tmp_data[i * other.getN() + j] = *other[i * other.getN() + j];
        }
    }

    _m = other.getM();
    _n = other.getN();

    delete [] _data;
    _data = tmp_data;
}

Matrix::~Matrix()
{
    delete [] _data;
}

unsigned int Matrix::getN() const
{
    return _n;
}

unsigned int Matrix::getM() const
{
    return _m;
}

Matrix&amp; Matrix::operator=(Matrix other)
{
    if(this != &amp;other)
    {
        double *tmp_data = new double[other.getM() * other.getN()];

        for(unsigned int i = 0; i &lt; other.getM(); ++i)
        {
            for(unsigned int j = 0; j &lt; other.getN(); ++j)
            {
                tmp_data[i * other.getN() + j] = *other[i * other.getN() + j];
            }
        }

        _m = other.getM();
        _n = other.getN();

        delete [] _data;
        _data = tmp_data;
    }

    return *this;
}

double* Matrix::operator[](unsigned const int&amp; i) const
{
    return &amp;_data[i * _n];
}

Matrix Matrix::operator*(const Matrix b) const
{
    Matrix result(this-&gt;getM(), b.getN());

    if(this-&gt;getN() != b.getM())
    {
        std::cerr &lt;&lt; &quot;Invalid Matrix size.&quot; &lt;&lt; std::endl;
        throw std::logic_error(&quot;Invalid Matrix size.&quot;);
    }

    for(unsigned int i = 0; i &lt; this-&gt;getM(); ++i)
    {
        for(unsigned int j = 0; j &lt; b.getN(); ++j)
        {
            double value = 0.0;
            for(unsigned int index = 0; index &lt; b.getM(); ++index)
            {
                value += (*this)[i][index] * b[index][j];
            }
            result[i][j] = value;
        }
    }

    return result;
}

void Matrix::print()
{
    for(unsigned int i = 0; i &lt; _m; ++i)
    {
        for(unsigned int j = 0; j &lt; _n; ++j)
        {
            std::cout &lt;&lt; (*this)[i][j];
            if(j &lt; _n - 1)
            {
                std::cout &lt;&lt; &quot; | &quot;;
            }
        }
        std::cout &lt;&lt; std::endl;
    }
}
</code></pre>
<p>Jetzt funktioniert es... Dachte ich ^^ solange, bis ich die print()-Funktion wieder genutzt habe. Seitdem stürzt das Programm wieder beim 3. oder 4. mal der Benutzung des Operators * ab. Wenn ich sie wieder aus meinem Code entferne gibt es &quot;keine&quot; Probleme mehr(bestimmt, aber man merkt es auf jeden Fall nicht einfach so). Woran könnte das liegen <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f615.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--confused_face"
      title=":confused:"
      alt="😕"
    /><br />
Danke noch mal,<br />
MfG<br />
DragonRaider</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407607</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407607</guid><dc:creator><![CDATA[DragonRaider]]></dc:creator><pubDate>Tue, 08 Jul 2014 15:38:05 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 16:28:40 GMT]]></title><description><![CDATA[<p>Dein Kopier<strong>konstruktor</strong> sieht eher wie eine Zuweisung aus. Du brauchst gar keinen temporären Puffer und das <code>delete[] _data;</code> ist tödlich.</p>
<p>Das Interface gefällt mir sehr viel besser, da hast Du aufmerksam gelesen.</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407625</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407625</guid><dc:creator><![CDATA[Furble Wurble]]></dc:creator><pubDate>Tue, 08 Jul 2014 16:28:40 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 16:32:01 GMT]]></title><description><![CDATA[<p>Dieser Thread wurde von Moderator/in <a href="http://www.c-plusplus.net/forum/u109509" rel="nofollow">SeppJ</a> aus dem Forum <a href="http://www.c-plusplus.net/forum/f10" rel="nofollow">C (C89, C99 und C11)</a> in das Forum <a href="http://www.c-plusplus.net/forum/f15" rel="nofollow">C++ (auch C++0x und C++11)</a> verschoben.</p>
<p>Im Zweifelsfall bitte auch folgende Hinweise beachten:<br />
<a href="http://www.c-plusplus.net/forum/39405" rel="nofollow">C/C++ Forum :: FAQ - Sonstiges :: Wohin mit meiner Frage?</a></p>
<p><em>Dieses Posting wurde automatisch erzeugt.</em></p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407627</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407627</guid><dc:creator><![CDATA[C++ Forumbot]]></dc:creator><pubDate>Tue, 08 Jul 2014 16:32:01 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 16:42:11 GMT]]></title><description><![CDATA[<p>Und wenn man statt Zeiger, new/delte/memset und &quot;Regel der Drei&quot; bzw. &quot;Regel der Fünf&quot; einfach std::vector nimmt, wird es viel einfacher.</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407634</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407634</guid><dc:creator><![CDATA[manni66]]></dc:creator><pubDate>Tue, 08 Jul 2014 16:42:11 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 18:09:33 GMT]]></title><description><![CDATA[<p>Hallo,<br />
@Furble Wurble: Freut mich, dass das Ganze jetzt besser ist <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f642.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--slightly_smiling_face"
      title=":)"
      alt="🙂"
    /> ich habe die Funktion print() auch noch const gemacht(verändert ja auch nichts) <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f603.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--grinning_face_with_big_eyes"
      title=":D"
      alt="😃"
    /> wegen dem Kopierkonstruktor: Da hast Du Recht, da hatte ich nicht richtig drüber nachgedacht. Das hat mein Problem gelöst <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f642.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--slightly_smiling_face"
      title=":)"
      alt="🙂"
    /> vielen Dank besonders an Dich, aber auch an alle Anderen die mir geholfen haben <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f642.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--slightly_smiling_face"
      title=":)"
      alt="🙂"
    /><br />
@manni66: Du hast Recht, so ginge es natürlich. Aber so habe ich doch viel mehr gelernt, oder? Jetzt weiß ich (wennn bestimmt auch noch nicht perfekt), wann man const bei Memberfunktionen verwenden sollte und wie ein Zuweisungsoperator und ein Kopierkonstruktor so ungefähr auszusehen haben. Und ich kenne mehr mögliche Fehlerquellen. Das alles wird mir in Zukunft helfen, eigene Klassen zu schreiben, die vielleicht nicht ganz so simpel sind/sich nicht &quot;umgehen&quot; lassen.<br />
MfG<br />
DragonRaider</p>
<p>PS.: Vielen Dank auch für's Verschieben <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f603.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--grinning_face_with_big_eyes"
      title=":D"
      alt="😃"
    /></p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407641</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407641</guid><dc:creator><![CDATA[DragonRaider]]></dc:creator><pubDate>Tue, 08 Jul 2014 18:09:33 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 18:53:29 GMT]]></title><description><![CDATA[<p>Hi,<br />
ich bin's noch mal. Ich war mir nicht sicher, ob das wirklich in nen anderen Thread sollte... Darum hier <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f642.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--slightly_smiling_face"
      title=":)"
      alt="🙂"
    /> Das Problem ist jetzt nämlich: Wenn ich den Zuweisungsoperator ganz pur nach dem Motto</p>
<pre><code>A = B;
</code></pre>
<p>verwende, stürzt das Programm ab ^^<br />
MfG<br />
DragonRaider</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407658</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407658</guid><dc:creator><![CDATA[DragonRaider]]></dc:creator><pubDate>Tue, 08 Jul 2014 18:53:29 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 19:41:39 GMT]]></title><description><![CDATA[<p>Hallo</p>
<p>Ich würde dir folgende Artikel nochmal ans Herz legen: <a href="http://www.c-plusplus.net/forum/232010-full" rel="nofollow">Überladung von Operatoren in C++ (Teil 1)</a>. Gerade wegen deinem Zuweisungsoperator.</p>
<p>Wegen deinem direkten Problem, solltest du deinem Kopiert-Konstruktor und deine Zuweisungs-Operator debuggen um zu sehen wo genau der Fehler auftritt.</p>
<p>Edit: Die Code-Zeile &quot;delete [] _data&quot; hast du hoffentlich aus dem Kopiekonstruktor entfernt. Zum anderen hast du innerhalb deines Kopiert-Konstruktors sowie auch im Zuweisungsoperator fehlerhafte Indexzugriffe ins Array, hier ein angepasster Zuweisungsoperator:</p>
<pre><code>Matrix&amp; Matrix::operator=(Matrix const&amp; other)
{
  if (this != &amp;other)
  {
    double *tmp_data = new double[other.getM() * other.getN()];

    for (unsigned int i = 0; i &lt; other.getM(); ++i)
      for (unsigned int j = 0; j &lt; other.getN(); ++j)
        // i muss mit getN multipliziert werden
        tmp_data[i * other.getN() + j] = other[i][j]; 
        // Beim zugriff auf _other_ wird nicht direkt ins _data gegriffen, sondern auf deinen 
        // ueberladenen Operator, den du implementiert hast. Ansonst koenntest du es noch so machen:
        //tmp_data[i * other.getN() + j] = other._data[i * other._n + j];

    _m = other.getM();
    _n = other.getN();

    delete[] _data;
    _data = tmp_data;
  }

  return *this;
}
</code></pre>
<p>Mfg mdn</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407661</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407661</guid><dc:creator><![CDATA[Marc-O]]></dc:creator><pubDate>Tue, 08 Jul 2014 19:41:39 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 19:29:31 GMT]]></title><description><![CDATA[<pre><code class="language-cpp">tmp_data[i * other.getN() + j] = *other[i * other.getN() + j];
</code></pre>
<p>die rechte Seite sieht seltsam aus...</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407665</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407665</guid><dc:creator><![CDATA[camper]]></dc:creator><pubDate>Tue, 08 Jul 2014 19:29:31 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Tue, 08 Jul 2014 22:47:00 GMT]]></title><description><![CDATA[<p>Ich finde den <code>operator[]</code> , der einen <code>double*</code> zurückgibt äusserst suspekt.</p>
<p>Der klassische Rat ist einen <code>double&amp; operator()(int x, int y);</code> zu implementieren und auf operator[] zu verzichten.</p>
<p>Ansonsten ist es recht schwierig einen Fehler zu erkennen, wenn Du nicht die aktuelle Implementierung postest.</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407681</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407681</guid><dc:creator><![CDATA[Furble Wurble]]></dc:creator><pubDate>Tue, 08 Jul 2014 22:47:00 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Wed, 09 Jul 2014 09:28:59 GMT]]></title><description><![CDATA[<p>Hallo,<br />
ich habe mich bemüht, schon einmal auf eure Einwände ein zu gehen. Im Code ist deshalb auch einiges Kommentiert.<br />
<a class="plugin-mentions-user plugin-mentions-a" href="https://www.c-plusplus.net/forum/uid/18177">@Marc-O</a>: _data ist private, also ist direkter zugriff nicht möglich(oder verwechsle ich da etwas?).</p>
<p>mat.h</p>
<pre><code>#ifndef MATRIX_LIBRARY_H
#define MATRIX_LIBRARY_H

class Matrix
{
public:
    Matrix(unsigned int m, unsigned int n);                //m = rows, n = columns
    Matrix(const Matrix &amp;other);
    ~Matrix();

    unsigned int getN() const;
    unsigned int getM() const;

    Matrix operator*(const Matrix b) const;
    double* operator[](unsigned const int&amp; i) const;
    double&amp; operator()(unsigned int i, unsigned int j);
    Matrix&amp; operator=(const Matrix other);

    void print() const;

private:
    unsigned int _n, _m;
    double *_data;
};

#endif
</code></pre>
<p>mat.cpp</p>
<pre><code>#include &quot;mat.h&quot;
#include &lt;stdexcept&gt;
#include &lt;cstdlib&gt;
#include &lt;cstring&gt;
#include &lt;iostream&gt;

Matrix::Matrix(unsigned int m, unsigned int n) : _n(n), _m(m)
{
    _data = new double[_m * _n];
    memset(_data, 0, sizeof(double) * _m * _n);
}

Matrix::Matrix(const Matrix&amp; other)
{
    _data = new double[other.getM() * other.getN()];

    /*for(unsigned int i = 0; i &lt; other.getM(); ++i)
    {
        for(unsigned int j = 0; j &lt; other.getN(); ++j)
        {
            _data[i * other.getN() + j] = *other[i * other.getN() + j];
        }
    }*/
    for(unsigned int i = 0; i &lt; other.getM() * other.getN(); ++i)
    {
        _data[i] = other[i][0];                                                                //Besser verständlich?
    }

    _m = other.getM();
    _n = other.getN();
}

Matrix::~Matrix()
{
    delete [] _data;
}

unsigned int Matrix::getN() const
{
    return _n;
}

unsigned int Matrix::getM() const
{
    return _m;
}

Matrix&amp; Matrix::operator=(const Matrix other)
{
    if(this != &amp;other)
    {
        double *tmp_data = new double[other.getM() * other.getN()];

        /*for(unsigned int i = 0; i &lt; other.getM(); ++i)
        {
            for(unsigned int j = 0; j &lt; other.getN(); ++j)
            {
                tmp_data[i * other.getN() + j] = *other[i * other.getN() + j];                   //Der Operator[] gibt die Addresse mit einem &quot;Offset&quot; zurück, sodass man die von **Arrays gewohnten Dinge machen kann.
            }                                                                                    //*other[i * other.getN() + j] ist somit das gleiche wie other[i * other.getN() + j][0]
        }*/
                                                                                                 //Jedoch ist diese Form sowieso ineffizient
        for(unsigned int i = 0; i &lt; other.getM() * other.getN(); ++i)
        {
            tmp_data[i] = other[i][0];                                                           //Besser verständlich?
        }

        _m = other.getM();
        _n = other.getN();

        delete [] _data;
        _data = tmp_data;
    }

    return *this;
}

double* Matrix::operator[](unsigned const int&amp; i) const                                          //Meiner Meinung nach intuitiver, da es sich verhält wie ein double** Array
{
    return &amp;_data[i * _n];
}

double&amp; Matrix::operator()(unsigned int i, unsigned int j)                                       //Auch gut ^^
{
    return _data[i * _n + j];
}

Matrix Matrix::operator*(const Matrix b) const
{
    Matrix result(this-&gt;getM(), b.getN());

    if(this-&gt;getN() != b.getM())
    {
        std::cerr &lt;&lt; &quot;Invalid Matrix size.&quot; &lt;&lt; std::endl;
        throw std::logic_error(&quot;Invalid Matrix size.&quot;);
    }

    for(unsigned int i = 0; i &lt; this-&gt;getM(); ++i)
    {
        for(unsigned int j = 0; j &lt; b.getN(); ++j)
        {
            double value = 0.0;
            for(unsigned int index = 0; index &lt; b.getM(); ++index)
            {
                value += (*this)[i][index] * b[index][j];
            }
            result[i][j] = value;
        }
    }

    return result;
}

void Matrix::print() const
{
    for(unsigned int i = 0; i &lt; _m; ++i)
    {
        for(unsigned int j = 0; j &lt; _n; ++j)
        {
            std::cout &lt;&lt; (*this)[i][j];
            if(j &lt; _n - 1)
            {
                std::cout &lt;&lt; &quot; | &quot;;
            }
        }
        std::cout &lt;&lt; std::endl;
    }
}
</code></pre>
<p>MfG<br />
DragonRaider</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407728</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407728</guid><dc:creator><![CDATA[DragonRaider]]></dc:creator><pubDate>Wed, 09 Jul 2014 09:28:59 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Wed, 09 Jul 2014 09:41:47 GMT]]></title><description><![CDATA[<p>Du kannst Dir übrigens in Deinem Kopierkonstruktor den Aufruf der get-Methoden sparen:</p>
<pre><code>//_m = other.getM();
_m = other._m; //usw.
</code></pre>
]]></description><link>https://www.c-plusplus.net/forum/post/2407730</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407730</guid><dc:creator><![CDATA[Belli]]></dc:creator><pubDate>Wed, 09 Jul 2014 09:41:47 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Wed, 09 Jul 2014 09:53:28 GMT]]></title><description><![CDATA[<pre><code class="language-cpp">_data[i] = other[i][0];                                                                //Besser verständlich?
</code></pre>
<p>leider immer noch falsch. Überlege nochmal genau, was du mit dem Argument i in deinem überladenen []-Operator anstellst.</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407732</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407732</guid><dc:creator><![CDATA[camper]]></dc:creator><pubDate>Wed, 09 Jul 2014 09:53:28 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Wed, 09 Jul 2014 13:05:53 GMT]]></title><description><![CDATA[<pre><code>class Matrix
{
public:
    Matrix(unsigned int m, unsigned int n);                //m = rows, n = columns
// wenn m und n einer Erläuterung bedürfen, warum sie dann nicht gleich so benennen? also _rows, _columns
// - dann sieht man u.a. auch viel schneller bei Tippfehlern durch, m und n sind ja nicht gerade einfach optische beim Überfliegen auseinanderzuhalten
// - und einbuchstabige Bezeichner haben in einem Interface sowieso nichts verloren - die hebt man sich für sehr kleine Scopes auf
    Matrix(const Matrix &amp;other);
    ~Matrix();

    unsigned int getN() const; // bin kein Fan von diesere Namenswahl für elementare Accesoren
    unsigned int getM() const;

    Matrix operator*(const Matrix b) const;               // der Parameter sollte eine Referenz sein
    double *operator[](unsigned const int&amp; i) const;      // Matrix ist eine &quot;Wert&quot;-Klasse - Wenn die Matrix konstant ist, sollten es auch die Elemente sein
                                                          // der Rückgabetyp sollte somit const double* sein
                                                          // eine non-const-Überladung ist dann natürlich ebenso erforderlich
    Matrix&amp; operator=(Matrix other);                      // siehe operator* (eine clevere Optimierung mit dieser Signatur existiert,
                                                          // aber besser ist es, erst mal die normale Technik zu lernen)

    void print();                                         // könnte wahrscheinlich const sein, soll ja sicher nicht die Matrix verändern

private:
    unsigned int _n, _m;
    double *_data;
};
</code></pre>
<pre><code>Matrix::Matrix(unsigned int m, unsigned int n) : _n(n), _m(m)
{
    _data = new double[_m * _n];                          // dass kann auch in der Initialisierungsliste passieren und sollte es der Konsitenz wegen auch
    memset(_data, 0, sizeof(double) * _m * _n);           // memset ist hier nur bedingt geeignet, fill/fill_n angemessen und die sofortige Initialisierung
                                                          // bei der Allokation die beste Variante: new foo[...]() oder in C++11 auch new foo[...]{}
}

// Symmetrie ist zwar nicht zwingend erforderlich, dürfte aber das Vertrauen in die Korrektheit des Codes erhöhen
// Die Verwendung der Initialisierungsliste ist auch hier zu empfehlen
Matrix::Matrix(const Matrix&amp; other)
{
    _data = new double[other.getM() * other.getN()];

    /*for(unsigned int i = 0; i &lt; other.getM(); ++i)
    {
        for(unsigned int j = 0; j &lt; other.getN(); ++j)
        {
            _data[i * other.getN() + j] = *other[i * other.getN() + j]; // falsch, da *other[i * other.getN() + j] zu other.data_[(i * other._n + j) * other._n] wird
                                                                        // Weil der fehlerhafte Zugriff beim Lesen stattfindet, ist es nicht unwahrscheinlich, dass das
                                                                        // Programm erst einmal läuft, nur mit fehlerhaften Daten.
                                                                        // Stünde der Unfug auf beiden Seiten, würde sich das Problem wahrscheinlich viel eher äußern,
                                                                        // und so die Fehlersuche beschleunigen.
// z.B:     _data[i * other.getN() + j] = other._data[i * other.getN() + j];
// oder     (*this)[i][j] = other[i][j];
        }
    }*/
    for(unsigned int i = 0; i &lt; other.getM() * other.getN(); ++i)
    {
//         _data[i] = other[i][0];                                                                //Besser verständlich?  - gleiches Problem, s.o.
// z.B.    _data[i] = other.data_[i];
// oder    (*this)[0][i] = other[0][i];
    }
 // Es gibt nat. auch noch passende Algorithmen in der Standardbibliothek
    _m = other.getM();
    _n = other.getN();
}

Matrix::~Matrix()
{
    delete [] _data;
}

unsigned int Matrix::getN() const
{
    return _n;
}

unsigned int Matrix::getM() const
{
    return _m;
}

Matrix&amp; Matrix::operator=(Matrix other)
{
    if(this != &amp;other)    // das ist sowieso immer erfüllt, wenn der other-Parameter keine Referenz ist - clever ist es bei dieser Signatur einfach den Inhalt von other zu stehlen,
                          // denn das ist sowieso schon eine temporäre Kopie des Argumentes, die nicht mehr gebraucht wird, ganz nebenbei erspart man sich den Code, der fast
                          // identisch zu dem im Konstruktor ist, nochmal zu schreiben (ggf. mit den gleichen oder anderen Fehlern).
    {
        double *tmp_data = new double[other.getM() * other.getN()]; // schön: erst neue Resourcen anfordern, bevor alte entsorgt werden
                                                                    // und damit wird der Test this != &amp;other erst recht überflüssig

        for(unsigned int i = 0; i &lt; other.getM(); ++i)
        {
            for(unsigned int j = 0; j &lt; other.getN(); ++j)
            {
                tmp_data[i * other.getN() + j] = *other[i * other.getN() + j]; // siehe Kopiekonstruktor
            }
        }

        _m = other.getM();
        _n = other.getN();

        delete [] _data;
        _data = tmp_data;
    }

    return *this;
}

double* Matrix::operator[](unsigned const int&amp; i) const
{
    return &amp;_data[i * _n];
}

Matrix Matrix::operator*(const Matrix b) const
{
    Matrix result(this-&gt;getM(), b.getN());

    if(this-&gt;getN() != b.getM())                             // sollte zweckmäßigerweise vor der Erzeugung von result kommen (Kleinigkeit)
    {
        std::cerr &lt;&lt; &quot;Invalid Matrix size.&quot; &lt;&lt; std::endl;
        throw std::logic_error(&quot;Invalid Matrix size.&quot;);
    }

    for(unsigned int i = 0; i &lt; this-&gt;getM(); ++i)
    {
        for(unsigned int j = 0; j &lt; b.getN(); ++j)
        {
            double value = 0.0;
            for(unsigned int index = 0; index &lt; b.getM(); ++index)
            {
                value += (*this)[i][index] * b[index][j];
            }
            result[i][j] = value;
        }
    }

    return result;
}
</code></pre>
]]></description><link>https://www.c-plusplus.net/forum/post/2407773</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407773</guid><dc:creator><![CDATA[camper]]></dc:creator><pubDate>Wed, 09 Jul 2014 13:05:53 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Wed, 09 Jul 2014 15:24:07 GMT]]></title><description><![CDATA[<p>Hi,<br />
ich überarbeite gerade den Code - Vielen Dank <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f642.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--slightly_smiling_face"
      title=":)"
      alt="🙂"
    /> In der Zeile</p>
<pre><code>... = other[I * other.getN() + j];
</code></pre>
<p>hatte ich wirklich nicht richtig nachgedacht. Müssen die Argumente bei Operatoren eigentlich immer Referenzen sein? Oder bringt das irgendwelche Vorteile(mal abgesehen davon, dass man sie u.U. verändern will)?<br />
Das Überprüfen des Pointers hatte ich aus dem Wikipediaartikel zur <em>Rule of Three</em>. Erst hatte ich im Zuweisungsoperator std::copy genutzt, was nicht funktioniert hatte... Jedoch liegt das am gleiche Problem wie das oben -&gt; mit other._data würde es funktionieren? Probiere ich gleich mal, der geupdatet Code kommt auch bald.<br />
Die &quot;Kürzel/Begriffe/Was-auch-immer&quot; m und n sind für Matrizen so festgelegt, jedoch wäre es tatsächlich wahrscheinlich leichter anstattdessen rows und cols o.ä. zu verwenden. Melde mich gleich noch mal, wenn der geupdatete Code fertig ist <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f642.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--slightly_smiling_face"
      title=":)"
      alt="🙂"
    /><br />
MfG<br />
DragonRaider</p>
<p>Edit: Ich verstehe den Sinn der const Überladung des Operators[] noch nicht so ganz, da dieser ja auch zur Bearbeitung der Matrix benutzt werden soll. Aber jetzt wo ich so drüber nachdenke... Bewirkt das dann einfach, dass ich den Wert des Pointers nicht ändern kann <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f615.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--confused_face"
      title=":confused:"
      alt="😕"
    /> (ziemlich dumme Frage, aber da bin ich mir gerade wirklich nicht sicher)</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407795</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407795</guid><dc:creator><![CDATA[DragonRaider]]></dc:creator><pubDate>Wed, 09 Jul 2014 15:24:07 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Wed, 09 Jul 2014 16:09:50 GMT]]></title><description><![CDATA[<p>Hallo,<br />
jetzt mal die aktuelle Version. Ich hoffe ich habe keinen Deiner Vorschläge für Verbesserungen vergessen. Letztendlich habe ich mich doch für die Namen m und n entschieden, da ich diese dadurch auswendig lerne, was in der Mathematik nicht schaden kann ^^</p>
<p>mat.h:</p>
<pre><code>#ifndef MATRIX_LIBRARY_H
#define MATRIX_LIBRARY_H

class Matrix
{
public:
    Matrix(unsigned int m, unsigned int n);                //m = rows, n = cols
    Matrix(const Matrix &amp;other);
    ~Matrix();

    unsigned int getN() const;
    unsigned int getM() const;

    Matrix operator*(const Matrix&amp; b) const;
    double* operator[](unsigned const int&amp; i) const;
    double&amp; operator()(unsigned const int&amp; i, unsigned const int&amp; j) const;
    Matrix&amp; operator=(const Matrix&amp; other);

    void print() const;

private:
    unsigned int _n, _m;
    double *_data;
};

#endif
</code></pre>
<p>mat.cpp:</p>
<pre><code>#include &quot;mat.h&quot;
#include &lt;stdexcept&gt;
#include &lt;cstdlib&gt;
#include &lt;cstring&gt;
#include &lt;iostream&gt;

#define DEBUG                                    //Sollte immer definiert sein wenn Anwendung nicht zu 100% sicher
#define DEBUGLEVEL_2                             //Etwas langsamer, aber leichter zu debuggen

Matrix::Matrix(unsigned int m, unsigned int n) : _n(n), _m(m), _data(new double[n * m])
{
    std::fill(_data, &amp;_data[n * m], 0.0);
}

Matrix::Matrix(const Matrix&amp; other) : _n(other._n), _m(other._m), _data(new double[other.getM() * other.getN()])
{
    std::copy(other._data, &amp;other._data[other._n * other._m - 1], _data);
}

Matrix::~Matrix()
{
    delete [] _data;
}

unsigned int Matrix::getN() const
{
    return _n;
}

unsigned int Matrix::getM() const
{
    return _m;
}

Matrix&amp; Matrix::operator=(const Matrix&amp; other)
{
    double *tmp_data = new double[other._m * other._n];

    std::copy(other._data, &amp;other._data[other._m * other._n], tmp_data);

    _m = other._m;
    _n = other._n;

    delete [] _data;
    _data = tmp_data;

    return *this;
}

double* Matrix::operator[](unsigned const int&amp; i) const                                          //Meiner Meinung nach intuitiver, da es sich verhält wie ein double** Array
{
    #ifdef DEBUG
    if(i &gt;= _m)
    {
        std::cerr &lt;&lt; &quot;Invalid index in operator[].&quot; &lt;&lt; std::endl;
        throw std::logic_error(&quot;Invalid index in operator[].&quot;);
    }
    #endif // DEBUG

    return &amp;_data[i * _n];
}

double&amp; Matrix::operator()(unsigned const int&amp; i, unsigned const int&amp; j) const                    //Auch gut ^^
{
    #ifdef DEBUG
    #ifdef DEBUGLEVEL_2
    if(i &gt;= _m)
    {
        std::cerr &lt;&lt; &quot;Invalid index i in operator[].&quot; &lt;&lt; std::endl;
        throw std::logic_error(&quot;Invalid index i in operator[].&quot;);
    }
    if(j &gt;= _n)
    {
        std::cerr &lt;&lt; &quot;Invalid index j in operator().&quot; &lt;&lt; std::endl;
        throw std::logic_error(&quot;Invalid index j in operator[].&quot;);
    }
    #else
    if(i &gt;= _m || j &gt;= _n)
    {
        std::cerr &lt;&lt; &quot;Invalid index in operator().&quot; &lt;&lt; std::endl;
        throw std::logic_error(&quot;Invalid index in operator().&quot;);
    }
    #endif
    #endif // DEBUG

    return _data[i * _n + j];
}

Matrix Matrix::operator*(const Matrix&amp; b) const
{
    #ifdef DEBUG
    if(this-&gt;_n != b._m)
    {
        std::cerr &lt;&lt; &quot;Invalid Matrix size.&quot; &lt;&lt; std::endl;
        throw std::logic_error(&quot;Invalid Matrix size.&quot;);
    }
    #endif

    Matrix result(this-&gt;_m, b._n);

    for(unsigned int i = 0; i &lt; this-&gt;_m; ++i)
    {
        for(unsigned int j = 0; j &lt; b._n; ++j)
        {
            double value = 0.0;
            for(unsigned int index = 0; index &lt; b._m; ++index)
            {
                value += (*this)[i][index] * b[index][j];
            }
            result[i][j] = value;
        }
    }

    return result;
}

void Matrix::print() const
{
    for(unsigned int i = 0; i &lt; _m; ++i)
    {
        for(unsigned int j = 0; j &lt; _n; ++j)
        {
            std::cout &lt;&lt; (*this)[i][j];
            if(j &lt; _n - 1)
            {
                std::cout &lt;&lt; &quot; | &quot;;
            }
        }
        std::cout &lt;&lt; std::endl;
    }
}
</code></pre>
<p>MfG<br />
DragonRaider</p>
]]></description><link>https://www.c-plusplus.net/forum/post/2407801</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407801</guid><dc:creator><![CDATA[DragonRaider]]></dc:creator><pubDate>Wed, 09 Jul 2014 16:09:50 GMT</pubDate></item><item><title><![CDATA[Reply to Gründe für malloc NULL zu returnen on Wed, 09 Jul 2014 16:57:57 GMT]]></title><description><![CDATA[<p>DragonRaider schrieb:</p>
<blockquote>
<p>Edit: Ich verstehe den Sinn der const Überladung des Operators[] noch nicht so ganz, da dieser ja auch zur Bearbeitung der Matrix benutzt werden soll. Aber jetzt wo ich so drüber nachdenke... Bewirkt das dann einfach, dass ich den Wert des Pointers nicht ändern kann <img
      src="https://www.c-plusplus.net/forum/plugins/nodebb-plugin-emoji/emoji/emoji-one/1f615.png?v=ab1pehoraso"
      class="not-responsive emoji emoji-emoji-one emoji--confused_face"
      title=":confused:"
      alt="😕"
    /> (ziemlich dumme Frage, aber da bin ich mir gerade wirklich nicht sicher)</p>
</blockquote>
<p>Gegenwärtig kann ich schreiben</p>
<pre><code class="language-cpp">const Matrix x(1,1);
x[0][0] = 42;
</code></pre>
<p>Wenn aber x konstant ist, ist es doch unlogisch, wenn ich trotzdem den Inhalt verändern kann.</p>
<p>Also muss die Überladung des []-Operators unterscheiden, ob sie für ein konstantes Objekt aufgerufen wird oder nicht. Analog dann für den ()-Operator.</p>
<p>Nebenbei bemerkt, ist es in der Regel nicht sinnvoll, arithmetische Typen wie int per Referenz zu übergeben.<br />
Ein assert ist bei Bereichsüberschreitungen in der Regel viel nützlicher als eine Exception.</p>
<pre><code class="language-cpp">const double* Matrix::operator[](unsigned i) const // für konstante Matizen
{
   assert(i &lt; _m &amp;&amp; &quot;invalid index&quot;);
   return _data + i * _n;
}
double* Matrix::operator[](unsigned i) // für modifizierbare Matrizen
{
   return const_cast&lt;double*&gt;( (*const_cast&lt;const Matrix*&gt;(this))[i] ); // vermeidet Codeduplikation
}

const double&amp; Matrix::operator()(unsigned i, unsigned j) const
{
   assert(j &lt; _n &amp;&amp; &quot;invalid index&quot;);
   return (*this)[i][j];
}
double* Matrix::operator[](unsigned i)
{
   return const_cast&lt;double*&gt;( (*const_cast&lt;const Matrix*&gt;(this))(i,j) );
}
</code></pre>
]]></description><link>https://www.c-plusplus.net/forum/post/2407810</link><guid isPermaLink="true">https://www.c-plusplus.net/forum/post/2407810</guid><dc:creator><![CDATA[camper]]></dc:creator><pubDate>Wed, 09 Jul 2014 16:57:57 GMT</pubDate></item></channel></rss>