0

I get

Stack around the variable 'a' was corrupted.

While trying out this code:

    #include "Stack.h"
    #include <iostream>

    struct product {
        int weight;
        float price;
    } ;

    void main(void){
        product a = {1, 4.0f};
        product b = {2, 5.0f};
        product c = {3, 6.0f};

        idStackTemplate<product, sizeof(product)> stack;

        stack.Add(&a);
        stack.Add(&b);
        stack.Add(&c);

        product * first, * second, *third;

        third = stack.Get();
        second = stack.Get();
        first = stack.Get();

        std::cout << first->price << "\t" << first->weight << "\n";
        std::cout << second->price << "\t" << second->weight << "\n";
        std::cout << third->price << "\t" << third->weight << "\n";
    }

Stack.h source code is located here!

Otherwise the code prints out the correct values.

I'm a beginner/intermediate in c/c++ so can you please help me understand how idStack works and what am I doing wrong.

I have tried creating stack object with idStack(type, next) macro - from what I understand you should put one of the elements of product for "next" parameter so that it calculates offset. It never worked correctly (with either weight or price) although I didn't get any stack corruption errors but the variables didn't print out correctly.

I have also seen some code in Doom 3 source code that uses dynamic allocation with memory pool which would kinda explain this but I can't see this technique being used here...

EDIT: I feel like I shoud allocate enough memory on heap (3*sizeof(a)) with that custom allocators and then initialize a at the beginning of that newly allocated memory. Am I leaning in the right direction?

4

1 に答える 1

3

このスタックの実装は侵入的です。スタック テンプレートが使用できるポインタがあることを期待しています。この場合、2 番目のテンプレート引数は、格納されているオブジェクトのサイズではなく、そのポインターへのオフセットを持つことを目的としています。

したがって、次の変更を加えることができます。

struct product {
    int weight;
    float price;
    struct product* next;   // <-- link pointer field
} ;


// the stack declaration:

idStackTemplate<product, offsetof(struct product, next)> stack;
//                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

言うまでもなく、この種のコンテナーは一般的には良い習慣とは見なされません。

于 2013-09-19T19:09:26.683 に答える