2013-02-26 4 views
0
#include <iostream> 
#include <stdlib.h> 

class circuitTypes{ 

protected: 
    static int size; 
    circuitTypes **Matrix; 
    int input1,input2; 
    int output1, output2; 

public: 

    circuitTypes() {}; 
    static int getSize() { return size; }; 
    static void upSize() { size++; }; 
    void ItemRegistry(); 
    virtual void setTruthTable()=0; 
    void setInputAndCalculateOutput(int a, int b); 
    int *getOutput(); 
}; 

int circuitTypes::size=0; 

int *circuitTypes::getOutput(){ 
    int Output[2]; 
    Output[0]=output1; 
    Output[1]=output2; 
    return Output; 
} 
void circuitTypes::ItemRegistry(){ 

    circuitTypes::upSize(); 
    int circuitSize=circuitTypes::getSize(); 

    if(circuitSize==1) 
     Matrix=(circuitTypes **)malloc(circuitSize*sizeof(circuitTypes *)); 
    else 
     Matrix=(circuitTypes **)realloc(Matrix,circuitSize*sizeof(circuitTypes *)); 
    if(Matrix==0){ 
     std::cout <<"No available memory \n"; 
     exit(1); 
    } 
    Matrix[circuitSize-1]=this; 
} 


void circuitTypes::setInputAndCalculateOutput(int a, int b){ 
    input1=a; 
    input2=b; 
    setTruthTable(); 
} 


class TypeA : private circuitTypes{ 

public: 
    TypeA() { ItemRegistry(); }; 
    void setTruthTable(); 
}; 

void TypeA::setTruthTable(){ 
    if (input1==0){ 
     if (input2==0){ 
      output1=0; 
      output2=0; 
     } 
     else{ 
      output1=0; 
      output2=1; 
     } 
    } 
    else{ 
     if (input2==0){ 
      output1=0; 
      output2=1; 
     } 
     else{ 
      output1=1; 
      output2=1; 
     } 
    } 
} 


class TypeB : private circuitTypes{ 
public: 
    TypeB() { ItemRegistry(); }; 
    void setTruthTable(); 
}; 

void TypeB::setTruthTable(){ 
    if (input1==0){ 
     if (input2==0){ 
      output1=0; 
      output2=0; 
     } 
     else{ 
      output1=0; 
      output2=1; 
     } 
    } 
    else{ 
     if (input2==0){ 
      output1=1; 
      output2=1; 
     } 
     else{ 
      output1=0; 
      output2=1; 
     } 
    } 
} 

void circuit (circuitTypes **Example, int a, int b){ 
    std::cout << "NIKKK"; 
    Example[0]->setInputAndCalculateOutput(a,b); 
    int Size=Example[0]->getSize(); 
    for (int i=1;i<Size;i++){ 

     Example[i]->setInputAndCalculateOutput(Example[i-1]->getOutput()[0],Example[i-1]->getOutput()[1]); 

    } 
    std::cout << "For input a= " << a << " and b= " << b << " the result is c= " << Example[Size-1]->getOutput()[0] << " and d=" << Example[Size-1]->getOutput()[1] << "\n"; 
} 


int main(){ 

    circuitTypes **Example; 
    TypeA A1,A2,A3; 
    TypeB B1,B2,B3; 
    for (int i=0;i<2;i++){ 

     for (int j=0;j<2;j++){ 
      circuit (Example,i,j); 
     } 

    } 

} 

Извините за размер кода, но поскольку я понятия не имею, где проблема, я решил опубликовать всю программу. Файл .cpp компилируются без каких-либо проблем в Ubuntu 11.10 (с г ++), но когда я пытаюсь выполнить файл a.out я получаю эту ошибку:Перераспределение памяти правильно в C++

* Glibc обнаруженной ./a.out: перераспределить (): недопустимый указатель: 0x003c2ff4 * *

======= Backtrace: =========

/lib/i386-linux-gnu/libc.so.6 (+ 0x721a2) [0x2b71a2]

/lib/i386-linux-gnu/libc.so.6(realloc+0x2a5)[0x2bb245]

./a.out[0x8048835]

./a.out[0x8048ca9]

./a.out[0x8048b2a]

/Библиотека/i386-Linux-ГНУ/Libc. so.6 (__ libc_start_main + 0xf3) [0x25e113]

./a.out[0x80486c1]

======= Карта памяти: ========

00110000 -0012c000 r-xp 00000000 08: 06 1311674 /lib/i386-linux-gnu/libgcc_s.so.1

0012c000-0012d000 г - р 0001b000 8:06 1311674 /lib/i386-linux-gnu/libgcc_s.so.1

и т. д.

Может ли кто-нибудь мне помочь?

+1

Мой совет: забудьте, что 'malloc' или' realloc' существует вообще. Вместо этого используйте 'std :: vector'. Что касается вашей таблицы истинности, для TypeA это просто «output1 = input1 & input2», 'output2 = input1 | input2'. Ваш 'getoutput' также возвращает адрес локальной переменной, поэтому его использование приводит к неопределенному поведению (опять же, легко излечивается путем возврата вектора вместо массива). –

+0

Сверху, внимательно посмотрите на свой 'main()', затем спросите ** и ответьте **, этот вопрос о себе: что такое значение 'Example', которое передается в функцию' circuit () '? – WhozCraig

+0

'realloc (0, size)' такой же, как 'malloc (size)'. Таким образом, вы могли бы просто сначала «Матрица», а затем сделать «Matrix = realloc (Matrix, n); if (! Matrix) oom(); ' –

ответ

0
  1. Плохо установить Matrix = realloc, так как вы никогда не сможете его освободить в случае сбоя realloc. Но вы все равно выходите, так что код не будет просачиваться, но это по-прежнему плохая практика.
  2. Вы просто объявляете circuitTypes ** Пример и используете его в схеме (Пример, i, j), не выделяя ему память. Вы, вероятно, захотите использовать Matrix для этого.
  3. Это чистое предположение: способ структурирования вашего кода заставляет меня думать, что вы хотите сделать Matrix static и использовать его вместо примера.
0
if(circuitSize==1) 
     Matrix=(circuitTypes **)malloc(circuitSize*sizeof(circuitTypes *)); 
    else 
     Matrix=(circuitTypes **)realloc(Matrix,circuitSize*sizeof(circuitTypes *)); 

Не понимаю if состояние здесь. Конечно, это должно быть if (Matrix == 0)? В противном случае вы рискуете попробовать realloc то, что у вас никогда не было malloc -ed в первую очередь.

Но я согласен с @JerryCoffin, что вы должны выбросить его и использовать std::vector.

Смежные вопросы