Created
November 7, 2021 18:33
-
-
Save nilput/bbc5693b689967f195669b9858c42670 to your computer and use it in GitHub Desktop.
An example showing usage of alloca() function, additionally: the stack pointer is printed after each call.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <alloca.h> | |
| #include <string.h> | |
| __attribute__((always_inline)) | |
| static inline void print_rsp() { | |
| #if defined(__x86_64__) | |
| void *rsp = NULL; | |
| asm ("mov %%rsp, %0;" | |
| :"=r"(rsp) /* output */ | |
| : /* input */ | |
| : /* clobbered register */ | |
| ); | |
| printf("RSP=%p\n", rsp); | |
| #endif | |
| } | |
| void accumulate(void) { | |
| int *nums = NULL; | |
| int count = 0; | |
| printf("RSP before alloca: "); print_rsp(); | |
| do { | |
| int *new_nums = alloca(sizeof(int) * ++count); | |
| if (nums) | |
| memcpy(new_nums, nums, sizeof(int) * (count - 1)); | |
| nums = new_nums; | |
| printf("RSP after allocating int[%d]: ", count); print_rsp(); | |
| printf("# "); | |
| } while (scanf("%d", nums + count - 1) == 1); | |
| count--; | |
| printf("Number of numbers stored: %d\n", count); | |
| printf("["); | |
| int sum = 0; | |
| for (int i=0; i<count; i++) { | |
| printf("%d%s", nums[i], (char *[]){",", ""}[i == count - 1]); | |
| sum += nums[i]; | |
| } | |
| printf("]\n"); | |
| printf("Sum: %d\n", sum); | |
| } | |
| int main(void) { | |
| printf("Accumulate v1.0\n"); | |
| printf("Enter numbers followed by 'quit'.\n\n"); | |
| printf("RSP at main: "); print_rsp(); | |
| accumulate(); | |
| printf("RSP after returning to main: "); print_rsp(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment