0

I wrote this function:

int einmaleins(int zahl, int *arr){
int e;
for(int i = 1; i<11; i++){
    e = zahl*i;
    arr[i-1]=e;
}

return 0;
}

int main(){
int arr[10] = {0};
einmaleins(2, &arr[10]);

return 0;
}

The Problem is the Pointer Array but when I start the program I got the following message: *** stack smashing detected ***: terminated

I really don't know what to do.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
kaan5353
  • 67
  • 5
  • 1
    `&arr[10]` - this is a pointer to eleventh element of the array. Which has only ten elements... – Eugene Sh. Nov 16 '21 at 20:49
  • @EugeneSh. right, strange code and I need coffee – Jabberwocky Nov 16 '21 at 20:51
  • Do you use an IDE? If not, I advise you to get one. Then learn about the debugger. You can set a "breakpoint" (or several) in your code and run the code. When it reaches the breakpoint, it will stop and you can examine the variables, and then step through your code, line by line, watching the variables. This is generally the quickest way to find problems like this one. – Mawg says reinstate Monica Nov 16 '21 at 20:52

2 Answers2

5

In this call

einmaleins(2, &arr[10]);

you are passing the address of the memory past the last element of the array.

Call the function like

einmaleins(2, arr);

The array designator used as an argument expression in the call is implicitly converted to a pointer to its first element,

In fact the call is equivalent to

einmaleins(2, &arr[0]);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

In the line

einmaleins(2, &arr[10]);

the expression &arr[10] will pass the address of the 11th element (in C, indexes are 0-based) to the function einmaleins. This is probably not what you want, as this will cause the function einmaleins to access the array out of bounds.

You probably want to pass the address of the first element, so you could write &arr[0] instead. However, it is normal to simply write arr. When you do that, the array will automatically decay to a pointer to the first element, so that it is equivalent to writing &arr[0].

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39