0

It's more of a conversation topic that a question. Look at the following code for calculating the nth Fibonacci number and print out all of them up to the nth(namespace std pressumed and the following is in the main):

int n=20;
int *a=new int; //notice NO size declaration
a[0]=1;
a[1]=1;
for(int i=2; i<n;i++){
    a[i]=a[i-1]+a[i-2];
}

for(int i=0; i<n;i++){
    cout<<a[i]<<endl;
}

So should it work? Does it work for you? Any comments as to whether it wouldn't work for someone? Thank you in advance. That's my personal method to allocate memory dynamically in 1D, but I can't find any documentation with this method, and I've been using it forever. Of course, I don't do the same on 2D. Thank you for reading.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Toinator
  • 36
  • 6

2 Answers2

0

So should it work?

No. Accessing any index other than a[0] produces undefined behavior, since it's outside the allocated memory.

Does it work for you?

It might appear to work in some cases. When you have undefined behavior, anything can happen; there's no requirement that the error be detected (see Why don't I get a segmentation fault when I write beyond the end of an array?). It's possible that the memory that it uses isn't in use for anything else, so it doesn't cause an obvious failure. But it could also cause corruption of data that's used by some unrelated part of the application or library; you might not notice the problem immediately.

A common symptom of undefined behavior is that seemingly innocuous changes cause unexpected changes in behavior. For instance, the program might work with a print statement in it, but fail when you remove that statement.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you, that's really helpful. For some reason instead of initializing properly like multidimensional arrays, I was using this method for 1D, until recently that it would raise an error to someone's computer. – Toinator May 07 '20 at 01:44
0

The way you are doing this is not "memory safe" because you are only allocating memory for a single integer and accessing subsequent addresses that have not been allocated. This is equivalent to declaring a definite sized array and accessing indexes larger than its size. There are a couple options to do what you want:

Allocating memory manually

Use malloc() to allocate the number of bytes you need. After using it you should use free(). The compiler does not do that for you.

int n=20;
int *a = malloc(sizeof(int) * n);
a[0]=1;
a[1]=1;
for(int i=2; i<n;i++){
    a[i]=a[i-1]+a[i-2];
}
free(a);

Using a C++ vector Container

Vectors are dynamically-sized arrays. They can change size automatically and are very useful. Read more here.

int n=20;
std::vector<int> a;
a.push_back(1);
a.push_back(1);
for(int i=2; i<n;i++){
    a.push_back(a[i-1]+a[i-2]);
}

Edit: clarify that you need to free() after using malloc().

rubemnobre
  • 100
  • 5