c - Segfault when a large parameter is passed -
my program supposed print out every nth character in string of text. first parameter defines "n" or increment between characters report on. second parameter optional, if specified, defines how many characters work on.
#include <stdio.h> #include <stdlib.h> #define max_str_len 100 int main(int argc, char **argv) { char string[max_str_len]; char *testval="this test, test. next sixty seconds, test of emergency broadcasting system."; if (argc<2) { printf("expected @ least 1 argument.\n"); return 1; } int inc=atoi(argv[1]); if (inc <=0) { printf("expected first argument positive number.\n"); return 1; } int max=max_str_len; if (argc==3) { max=atoi(argv[2]); if (max<0) max=max_str_len; } int i=0; while(i < max) { string[i]=testval[i]; // gdb says seg fault occurs i++; } string[i]=0; i=0; while(string[i]!=0) { printf("the %d char %c\n",i,string[i]); = + inc; } return 0; }
running "./prog3 5 40" works fine, running "./prog3 5 150" causes seg fault.
./prog3 5 150 8 segmentation fault
this work better. need make string buffer large enough hold data put it. segmentation fault had comes writing memory address not allowed used program.
#include <stdio.h> #include <stdlib.h> #define max_str_len 100 int main(int argc, char **argv) { char *testval="this test, test. next sixty seconds, test of emergency broadcasting system."; if (argc<2) { printf("expected @ least 1 argument.\n"); return 1; } int inc=atoi(argv[1]); if (inc <=0) { printf("expected first argument positive number.\n"); return 1; } int max=max_str_len; if (argc==3) { max=atoi(argv[2]); if (max<0) max=max_str_len; } char string[max]; int i=0; while(i < max) { string[i]=testval[i]; i++; } string[i]=0; i=0; while(string[i]!=0) { printf("the %d char %c\n",i,string[i]); = + inc; } return 0; }
Comments
Post a Comment