Segmentation fault in number printing program
当我运行此程序时,会出现分段错误??
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | #include <stdio.h> #include <stdlib.h> #include <string.h> static char* exe; void usage(void) { printf("Usage: %s <number of integers> ", exe); } int main(int argc, char** argv) { //This program reads in n integers and outputs them/ //in reverse order. However, for some odd reason, I/ //am getting an error when I run it with no command/ //line arguments. It is supposed to display helpful/ //usage information out, but instead it segfaults??/ exe = malloc(50 * sizeof(*exe)); strncpy(exe, argv[0], 49); if(argc != 2) { usage(); exit(0); } int n = atoi(argv[1]); int* numbers = malloc(n * sizeof(*numbers)); int i; for(i = 0; i < n; i++) { scanf("%d ", &numbers[i]); } for(i = 9; i >= 0; i--) { printf("%d:\t%d ", 10 - i, numbers[i]); } free(numbers); free(exe); return 0; } |
这是因为
您需要确保您的
尝试在
1 | exe[49] = '\0'; |
变量