Разница между этими двумя кодами (почему мой массив занимает дополнительное место, даже если я дал ему ограничение) - PullRequest
0 голосов
/ 02 июля 2019

Я объявил массив размером 10 двумя способами (один - путем непосредственного присвоения, а другой - присвоения значения переменной (здесь это размер) и передачи его в массив. Проблема в первом случае, было ограничение на размер массива, когда я перешел предел, но во втором случае размер массива был превышен, и все же я не получаю сообщение об ошибке) я могу знать, что происходит ??заранее спасибо!:)

PS: Когда я увидел адрес, все было в порядке.

#include<iostream>
using namespace std;

//global declaration
int top =-1;

void push(int array[],int value){
 top = top+1;
 array[top] = value;
 cout<<"Pushed "<<value<<" at "<< top << " position"<< endl;

}

void pop(){
    top = top -1;
}


void Gettop(int size){
    cout<< "top is at "<< top << " of "<<size<<endl;
}

bool isEmpty(){
    if(top == -1){
        return true;
    }
}

int GetTopval(int array[]){
    return array[top];
}



int main(){
   int size=10;

   int oldArray[size];

   push(oldArray,2);
   push(oldArray,23);
   push(oldArray,22);
   push(oldArray,24);
   push(oldArray,242);
   push(oldArray,22);
   push(oldArray,21);
      push(oldArray,2);
   push(oldArray,23);
   push(oldArray,22);
   push(oldArray,24);
   push(oldArray,242);
   push(oldArray,22);
   push(oldArray,21);
     push(oldArray,242);
   push(oldArray,22);
   push(oldArray,21);
   pop();
   push(oldArray,211);
   int value = GetTopval(oldArray);

   cout<< "VAlue : "<< value<<endl;

cout<< "printing the Array: "<<endl;
for(int i=0;i<15;i++){
    int *temp = &oldArray[i];
    cout<<oldArray[i]<<" with i as "<< i <<endl;
    cout<<"at address : "<< temp <<endl;
}


    return 0;
}

Другой случай:

#include<iostream>
using namespace std;

//global declaration
int top =-1;

void push(int array[],int value){
 top = top+1;
 array[top] = value;
 cout<<"Pushed "<<value<<" at "<< top << " position"<< endl;

}

void pop(){
    top = top -1;
}


void Gettop(int size){
    cout<< "top is at "<< top << " of "<<size<<endl;
}

bool isEmpty(){
    if(top == -1){
        return true;
    }
}

int GetTopval(int array[]){
    return array[top];
}



int main(){
   int size=10;

   int oldArray[size];

   push(oldArray,2);
   push(oldArray,23);
   push(oldArray,22);
   push(oldArray,24);
   push(oldArray,242);
   push(oldArray,22);
   push(oldArray,21);
      push(oldArray,2);
   push(oldArray,23);
   push(oldArray,22);
   push(oldArray,24);
   push(oldArray,242);
   push(oldArray,22);
   push(oldArray,21);
     push(oldArray,242);
   push(oldArray,22);
   push(oldArray,21);
   pop();
   push(oldArray,211);
   int value = GetTopval(oldArray);

   cout<< "VAlue : "<< value<<endl;

cout<< "printing the Array: "<<endl;
for(int i=0;i<15;i++){
    int *temp = &oldArray[i];
    cout<<oldArray[i]<<" with i as "<< i <<endl;
    cout<<"at address : "<< temp <<endl;
}


    return 0;
}

Вывод для case2:

Pushed 2 at 0 position
Pushed 23 at 1 position
Pushed 22 at 2 position
Pushed 24 at 3 position
Pushed 242 at 4 position
Pushed 22 at 5 position
Pushed 21 at 6 position
Pushed 2 at 7 position
Pushed 23 at 8 position
Pushed 22 at 9 position
Pushed 24 at 10 position
Pushed 242 at 11 position
Pushed 22 at 12 position
Pushed 21 at 13 position
Pushed 242 at 14 position
Pushed 22 at 15 position
Pushed 21 at 16 position
Pushed 211 at 16 position
VAlue : 211
printing the Array: 
2 with i as 0
at address : 0x7ffffbb707c0
23 with i as 1
at address : 0x7ffffbb707c4
22 with i as 2
at address : 0x7ffffbb707c8
24 with i as 3
at address : 0x7ffffbb707cc
242 with i as 4
at address : 0x7ffffbb707d0
22 with i as 5
at address : 0x7ffffbb707d4
21 with i as 6
at address : 0x7ffffbb707d8
2 with i as 7
at address : 0x7ffffbb707dc
23 with i as 8
at address : 0x7ffffbb707e0
22 with i as 9
at address : 0x7ffffbb707e4
24 with i as 10
at address : 0x7ffffbb707e8
242 with i as 11
at address : 0x7ffffbb707ec
22 with i as 12
at address : 0x7ffffbb707f0
13 with i as 13
at address : 0x7ffffbb707f4
242 with i as 14
at address : 0x7ffffbb707f8


Выход для case1:

Pushed 2 at 0 position
Pushed 23 at 1 position
Pushed 22 at 2 position
Pushed 24 at 3 position
Pushed 242 at 4 position
Pushed 22 at 5 position
Pushed 21 at 6 position
Pushed 2 at 7 position
Pushed 23 at 8 position
Pushed 22 at 9 position
Pushed 24 at 10 position
Pushed 242 at 11 position
Pushed 22 at 12 position
Pushed 21 at 13 position
Pushed 242 at 14 position
Pushed 22 at 15 position
Pushed 21 at 16 position
Pushed 211 at 16 position
VAlue : 211
printing the Array: 
2 with i as 0
at address : 0x7fff8be0b780
23 with i as 1
at address : 0x7fff8be0b784
22 with i as 2
at address : 0x7fff8be0b788
24 with i as 3
at address : 0x7fff8be0b78c
242 with i as 4
at address : 0x7fff8be0b790
22 with i as 5
at address : 0x7fff8be0b794
21 with i as 6
at address : 0x7fff8be0b798
2 with i as 7
at address : 0x7fff8be0b79c
23 with i as 8
at address : 0x7fff8be0b7a0
22 with i as 9
at address : 0x7fff8be0b7a4
24 with i as 10
at address : 0x7fff8be0b7a8
242 with i as 11
at address : 0x7fff8be0b7ac
22 with i as 12
at address : 0x7fff8be0b7b0
21 with i as 13
at address : 0x7fff8be0b7b4
242 with i as 14
at address : 0x7fff8be0b7b8
*** stack smashing detected ***: <unknown> terminated
Aborted (core dumped)

1 Ответ

2 голосов
/ 02 июля 2019

Нет «лишних пробелов». У вас есть массив размером 10, но вы обращаетесь к нему за пределами и тем самым вызываете неопределенное поведение.

После вызова более 10 раз:

void push(int array[],int value){
 top = top+1;
 array[top] = value;
 cout<<"Pushed "<<value<<" at "<< top << " position"<< endl;

}

вы получите доступ к array[10], который уже вышел за пределы.

В двух словах, неопределенное поведение означает: компилятору не требуется предупреждать вас или выдавать ошибку, ваш код может показаться работающим, но при его запуске может произойти все что угодно. Стандарт c ++ не определяет, что происходит, когда вы нарушаете правила.

...