mercredi 24 octobre 2018

Accessing memory at negative indexes of array in C++ does not return garbage

I wrote the following program to search of a particular string in a given array of string. I made an error in the search function and wrote i-- instead of i++.

#include <iostream>
#include <string>
using namespace std;

int search(string S[], int pos, string s)
{
    for(int i=0; i<pos; i--) {
        cout << i << " : " << S[i] << "\n";
        if (S[i] == s) {
            cout << "Inside Return ->\n";
            cout << i << " / " << S[i] << " / " << s << "\n";
            return i;
        }
    }
    return -1;
}

int main()
{
    string S[] = {"abc", "def", "pqr", "xyz"};
    string s = "def";
    cout << search(S,2,s) << "\n";
    return 0;
}

Logically the loop is an infinite loop and should not stop but what I observed was that the if condition was true for each search and the function returned -1.

I printed the values and noticed that the value of S[-1] is always same as the third argument passed to the function (the string to be searched) due to which the loop was returning -1 every time.

Is this something that g++ is doing or is it related to the way memory is allocated for the formal arguments of the function?

Output of the above code -

 0 : abc
-1 : def
Inside Return ->
-1 / def / def

PS - I am using g++ (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0

Aucun commentaire:

Enregistrer un commentaire