std::bad_alloc in Gaussian Elimination written based on a pseudo-code












0















I used this pseudo-code:



 h := 1 /* Initialization of the pivot row */
k := 1 /* Initialization of the pivot column */
while h ≤ m and k ≤ n
/* Find the k-th pivot: */
i_max := argmax (i = h ... m, abs(A[i, k]))
if A[i_max, k] = 0
/* No pivot in this column, pass to next column */
k := k+1
else
swap rows(h, i_max)
/* Do for all rows below pivot: */
for i = h + 1 ... m:
f := A[i, k] / A[h, k]
/* Fill with zeros the lower part of pivot column: */
A[i, k] := 0
/* Do for all remaining elements in current row: */
for j = k + 1 ... n:
A[i, j] := A[i, j] - A[h, j] * f
/* Increase pivot row and column */
h := h+1
k := k+1


To write this code (Gaussian Elimination):



#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>

typedef std::vector<std::vector<int>> matrix;
typedef long long ll;

void inverse_matrix(matrix &mat)
{
ll h = 1, k =1;
auto m = mat.size(), n = mat[0].size();


while (h <= m && k <= n)
{
ll i_max = 0;
for (ll i = h; i <= m; ++i)
{
i_max = std::fmax(i, std::abs(mat[i][k]));
}

if (mat[i_max][k] == 0)
{
++k;
}

auto temp = mat[h];
mat[h] = mat[i_max];
mat[i_max] = temp;

for (auto j = h + 1; j <= m; ++j)
{
auto f = mat[j][k] / mat[h][k];
mat[j][k] = 0;

for (auto v = k + 1; v <= n; ++v)
{
mat[j][v] = mat[j][v] - mat[h][j] * f;
}
}

++h;
++k;
}
}

int main() {
matrix mat = {{2, 2}, {4, 5}};
inverse_matrix(mat);

return 0;
}


But I get this error:




terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc



This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.




What's wrong? I copied the pseudo-code to a tee.










share|improve this question


















  • 1





    I believe you have undefined behavior because you are indexing out of bounds: for (auto j = h + 1; j <= m; ++j) so not sure what is going on here. Try using compiler warnings or -fsanitize flags of your compiler to guide you

    – JVApen
    Nov 14 '18 at 7:39











  • I am surprised that you try to calculate the inverse of a int matrix ...

    – Damien
    Nov 14 '18 at 8:00











  • I don't understand your use of std::fmax

    – Damien
    Nov 14 '18 at 9:05


















0















I used this pseudo-code:



 h := 1 /* Initialization of the pivot row */
k := 1 /* Initialization of the pivot column */
while h ≤ m and k ≤ n
/* Find the k-th pivot: */
i_max := argmax (i = h ... m, abs(A[i, k]))
if A[i_max, k] = 0
/* No pivot in this column, pass to next column */
k := k+1
else
swap rows(h, i_max)
/* Do for all rows below pivot: */
for i = h + 1 ... m:
f := A[i, k] / A[h, k]
/* Fill with zeros the lower part of pivot column: */
A[i, k] := 0
/* Do for all remaining elements in current row: */
for j = k + 1 ... n:
A[i, j] := A[i, j] - A[h, j] * f
/* Increase pivot row and column */
h := h+1
k := k+1


To write this code (Gaussian Elimination):



#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>

typedef std::vector<std::vector<int>> matrix;
typedef long long ll;

void inverse_matrix(matrix &mat)
{
ll h = 1, k =1;
auto m = mat.size(), n = mat[0].size();


while (h <= m && k <= n)
{
ll i_max = 0;
for (ll i = h; i <= m; ++i)
{
i_max = std::fmax(i, std::abs(mat[i][k]));
}

if (mat[i_max][k] == 0)
{
++k;
}

auto temp = mat[h];
mat[h] = mat[i_max];
mat[i_max] = temp;

for (auto j = h + 1; j <= m; ++j)
{
auto f = mat[j][k] / mat[h][k];
mat[j][k] = 0;

for (auto v = k + 1; v <= n; ++v)
{
mat[j][v] = mat[j][v] - mat[h][j] * f;
}
}

++h;
++k;
}
}

int main() {
matrix mat = {{2, 2}, {4, 5}};
inverse_matrix(mat);

return 0;
}


But I get this error:




terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc



This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.




What's wrong? I copied the pseudo-code to a tee.










share|improve this question


















  • 1





    I believe you have undefined behavior because you are indexing out of bounds: for (auto j = h + 1; j <= m; ++j) so not sure what is going on here. Try using compiler warnings or -fsanitize flags of your compiler to guide you

    – JVApen
    Nov 14 '18 at 7:39











  • I am surprised that you try to calculate the inverse of a int matrix ...

    – Damien
    Nov 14 '18 at 8:00











  • I don't understand your use of std::fmax

    – Damien
    Nov 14 '18 at 9:05
















0












0








0








I used this pseudo-code:



 h := 1 /* Initialization of the pivot row */
k := 1 /* Initialization of the pivot column */
while h ≤ m and k ≤ n
/* Find the k-th pivot: */
i_max := argmax (i = h ... m, abs(A[i, k]))
if A[i_max, k] = 0
/* No pivot in this column, pass to next column */
k := k+1
else
swap rows(h, i_max)
/* Do for all rows below pivot: */
for i = h + 1 ... m:
f := A[i, k] / A[h, k]
/* Fill with zeros the lower part of pivot column: */
A[i, k] := 0
/* Do for all remaining elements in current row: */
for j = k + 1 ... n:
A[i, j] := A[i, j] - A[h, j] * f
/* Increase pivot row and column */
h := h+1
k := k+1


To write this code (Gaussian Elimination):



#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>

typedef std::vector<std::vector<int>> matrix;
typedef long long ll;

void inverse_matrix(matrix &mat)
{
ll h = 1, k =1;
auto m = mat.size(), n = mat[0].size();


while (h <= m && k <= n)
{
ll i_max = 0;
for (ll i = h; i <= m; ++i)
{
i_max = std::fmax(i, std::abs(mat[i][k]));
}

if (mat[i_max][k] == 0)
{
++k;
}

auto temp = mat[h];
mat[h] = mat[i_max];
mat[i_max] = temp;

for (auto j = h + 1; j <= m; ++j)
{
auto f = mat[j][k] / mat[h][k];
mat[j][k] = 0;

for (auto v = k + 1; v <= n; ++v)
{
mat[j][v] = mat[j][v] - mat[h][j] * f;
}
}

++h;
++k;
}
}

int main() {
matrix mat = {{2, 2}, {4, 5}};
inverse_matrix(mat);

return 0;
}


But I get this error:




terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc



This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.




What's wrong? I copied the pseudo-code to a tee.










share|improve this question














I used this pseudo-code:



 h := 1 /* Initialization of the pivot row */
k := 1 /* Initialization of the pivot column */
while h ≤ m and k ≤ n
/* Find the k-th pivot: */
i_max := argmax (i = h ... m, abs(A[i, k]))
if A[i_max, k] = 0
/* No pivot in this column, pass to next column */
k := k+1
else
swap rows(h, i_max)
/* Do for all rows below pivot: */
for i = h + 1 ... m:
f := A[i, k] / A[h, k]
/* Fill with zeros the lower part of pivot column: */
A[i, k] := 0
/* Do for all remaining elements in current row: */
for j = k + 1 ... n:
A[i, j] := A[i, j] - A[h, j] * f
/* Increase pivot row and column */
h := h+1
k := k+1


To write this code (Gaussian Elimination):



#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>

typedef std::vector<std::vector<int>> matrix;
typedef long long ll;

void inverse_matrix(matrix &mat)
{
ll h = 1, k =1;
auto m = mat.size(), n = mat[0].size();


while (h <= m && k <= n)
{
ll i_max = 0;
for (ll i = h; i <= m; ++i)
{
i_max = std::fmax(i, std::abs(mat[i][k]));
}

if (mat[i_max][k] == 0)
{
++k;
}

auto temp = mat[h];
mat[h] = mat[i_max];
mat[i_max] = temp;

for (auto j = h + 1; j <= m; ++j)
{
auto f = mat[j][k] / mat[h][k];
mat[j][k] = 0;

for (auto v = k + 1; v <= n; ++v)
{
mat[j][v] = mat[j][v] - mat[h][j] * f;
}
}

++h;
++k;
}
}

int main() {
matrix mat = {{2, 2}, {4, 5}};
inverse_matrix(mat);

return 0;
}


But I get this error:




terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc



This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.




What's wrong? I copied the pseudo-code to a tee.







c++ matrix c++14 gaussian






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 14 '18 at 7:31









Masoud NazemiMasoud Nazemi

112




112








  • 1





    I believe you have undefined behavior because you are indexing out of bounds: for (auto j = h + 1; j <= m; ++j) so not sure what is going on here. Try using compiler warnings or -fsanitize flags of your compiler to guide you

    – JVApen
    Nov 14 '18 at 7:39











  • I am surprised that you try to calculate the inverse of a int matrix ...

    – Damien
    Nov 14 '18 at 8:00











  • I don't understand your use of std::fmax

    – Damien
    Nov 14 '18 at 9:05
















  • 1





    I believe you have undefined behavior because you are indexing out of bounds: for (auto j = h + 1; j <= m; ++j) so not sure what is going on here. Try using compiler warnings or -fsanitize flags of your compiler to guide you

    – JVApen
    Nov 14 '18 at 7:39











  • I am surprised that you try to calculate the inverse of a int matrix ...

    – Damien
    Nov 14 '18 at 8:00











  • I don't understand your use of std::fmax

    – Damien
    Nov 14 '18 at 9:05










1




1





I believe you have undefined behavior because you are indexing out of bounds: for (auto j = h + 1; j <= m; ++j) so not sure what is going on here. Try using compiler warnings or -fsanitize flags of your compiler to guide you

– JVApen
Nov 14 '18 at 7:39





I believe you have undefined behavior because you are indexing out of bounds: for (auto j = h + 1; j <= m; ++j) so not sure what is going on here. Try using compiler warnings or -fsanitize flags of your compiler to guide you

– JVApen
Nov 14 '18 at 7:39













I am surprised that you try to calculate the inverse of a int matrix ...

– Damien
Nov 14 '18 at 8:00





I am surprised that you try to calculate the inverse of a int matrix ...

– Damien
Nov 14 '18 at 8:00













I don't understand your use of std::fmax

– Damien
Nov 14 '18 at 9:05







I don't understand your use of std::fmax

– Damien
Nov 14 '18 at 9:05














1 Answer
1






active

oldest

votes


















1














You have a few issues here.



First of, you did not copy the code correctly (for instance, line 5 of the pseudo-code - that's including the comment line). What you should be looking for is the index of the maximal value, instead you are comparing the value with the index. To make matters worse, you do it in a way that only ends up storing the final comparison, because you overwrite all of the other results.



Second, the pseudo-code runs indices from 1-n, as you know C++ does not, instead we use 0-based indexing. As for the error, std::bad_alloc suggests an allocation failed, that's most likely the line: auto temp = mat[h];, where h is out of bounds due to your 1-based counting approach.



Perhaps as a side note, you could also replace your swap with std::swap, this might improve the performance slightly as it will probably avoid copying and rely on moving instead.






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53295095%2fstdbad-alloc-in-gaussian-elimination-written-based-on-a-pseudo-code%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    You have a few issues here.



    First of, you did not copy the code correctly (for instance, line 5 of the pseudo-code - that's including the comment line). What you should be looking for is the index of the maximal value, instead you are comparing the value with the index. To make matters worse, you do it in a way that only ends up storing the final comparison, because you overwrite all of the other results.



    Second, the pseudo-code runs indices from 1-n, as you know C++ does not, instead we use 0-based indexing. As for the error, std::bad_alloc suggests an allocation failed, that's most likely the line: auto temp = mat[h];, where h is out of bounds due to your 1-based counting approach.



    Perhaps as a side note, you could also replace your swap with std::swap, this might improve the performance slightly as it will probably avoid copying and rely on moving instead.






    share|improve this answer






























      1














      You have a few issues here.



      First of, you did not copy the code correctly (for instance, line 5 of the pseudo-code - that's including the comment line). What you should be looking for is the index of the maximal value, instead you are comparing the value with the index. To make matters worse, you do it in a way that only ends up storing the final comparison, because you overwrite all of the other results.



      Second, the pseudo-code runs indices from 1-n, as you know C++ does not, instead we use 0-based indexing. As for the error, std::bad_alloc suggests an allocation failed, that's most likely the line: auto temp = mat[h];, where h is out of bounds due to your 1-based counting approach.



      Perhaps as a side note, you could also replace your swap with std::swap, this might improve the performance slightly as it will probably avoid copying and rely on moving instead.






      share|improve this answer




























        1












        1








        1







        You have a few issues here.



        First of, you did not copy the code correctly (for instance, line 5 of the pseudo-code - that's including the comment line). What you should be looking for is the index of the maximal value, instead you are comparing the value with the index. To make matters worse, you do it in a way that only ends up storing the final comparison, because you overwrite all of the other results.



        Second, the pseudo-code runs indices from 1-n, as you know C++ does not, instead we use 0-based indexing. As for the error, std::bad_alloc suggests an allocation failed, that's most likely the line: auto temp = mat[h];, where h is out of bounds due to your 1-based counting approach.



        Perhaps as a side note, you could also replace your swap with std::swap, this might improve the performance slightly as it will probably avoid copying and rely on moving instead.






        share|improve this answer















        You have a few issues here.



        First of, you did not copy the code correctly (for instance, line 5 of the pseudo-code - that's including the comment line). What you should be looking for is the index of the maximal value, instead you are comparing the value with the index. To make matters worse, you do it in a way that only ends up storing the final comparison, because you overwrite all of the other results.



        Second, the pseudo-code runs indices from 1-n, as you know C++ does not, instead we use 0-based indexing. As for the error, std::bad_alloc suggests an allocation failed, that's most likely the line: auto temp = mat[h];, where h is out of bounds due to your 1-based counting approach.



        Perhaps as a side note, you could also replace your swap with std::swap, this might improve the performance slightly as it will probably avoid copying and rely on moving instead.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 14 '18 at 7:46

























        answered Nov 14 '18 at 7:40









        QubitQubit

        962315




        962315
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53295095%2fstdbad-alloc-in-gaussian-elimination-written-based-on-a-pseudo-code%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Florida Star v. B. J. F.

            Danny Elfman

            Lugert, Oklahoma