-2

I am trying to decrement a pointer while setting values to what the pointer is poiting to. When setting the values they show that they have been properly set, but when trying to retrieve them again it doesnt return the right values. Why is this, and how can I get it to work?

This is the code I tried:

int a = 0; int* sp = &a; int* start_sp = &a; for (int i = 0; i <= n; i++) { *sp = i; printf("%d, %d\n", *sp, sp); sp--; } sp = start_sp; printf("\n"); for (int i = 0; i <= n; i++) { printf("%d, %d\n", *sp, sp); sp--; } 

The output I get is:

0, 6291028 1, 6291024 2, 6291020 3, 6291016 4, 6291012 0, 6291028 1, 6291024 0, 6291020 6283584, 6291016 0, 6291012 

Why is this happening?

19
  • 1
    You have undefined behavior when your pointer is going out of bounds of the variable a. Commented Jan 28, 2024 at 15:37
  • You're modifying memory you never allocated. how can I get it to work? By actually using memory you own. Commented Jan 28, 2024 at 15:37
  • 1
    You’re both trying to smash your stack and printing pointers with the wrong format specifier? Commented Jan 28, 2024 at 15:38
  • 1
    Also note that the correct format to print a void * pointer is %p, and a cast is needed. Mismatching format specifier and argument type also leads to undefined behavior. Commented Jan 28, 2024 at 15:38
  • I have been tasked with using a local array declaration that saves all data on the stack of unknown size. As far as I have understood (this very well might be wrong) using malloc the data will be stored on the heap, and the same with a normal array declaration, but that wouldn't really work since the array is of an unknown size. How would I do this then? @tkausl Commented Jan 28, 2024 at 15:48

1 Answer 1

1

Why is this, and how can I get it to work?

As you access the memory which does not belong to any object, you invoke an undefined behavior.

To work you need to assign the pointer with the reference of the object (in this case an element of array) and you need to be sure that sp - n references the same array;

int main(void) { int n = 6; int *a = malloc(sizeof(*a) * n); int* sp = a + n - 1; int* start_sp = sp; for (int i = 0; i < n; i++) { *sp = i; printf("%d, %p\n", *sp, (void *)sp); sp--; } sp = start_sp; printf("\n"); for (int i = 0; i < n; i++) { printf("%d, %p\n", *sp, (void *)sp); sp--; } free(a); } 
Sign up to request clarification or add additional context in comments.

2 Comments

That needs to be int* sp = a + n; if the sp is going to be decremented through the loops.
Yes, but wouldn't this be stored on the heap? I should have added this in the discription but I am trying to have it saved on the stack @ikegami

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.