2015-10-02 22 views
0

我的程序應該打印出一串文本中的每第n個字符。第一個參數定義要報告的字符之間的「n」或增量。第二個參數是可選的,但如果指定,則定義要處理的字符數。通過大參數時發生段錯誤

#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 is a test, this is only a test. For the next sixty seconds, this will be a test of the emergency broadcasting system."; 

    if (argc<2) { 
      printf("Expected at least one argument.\n"); 
      return 1; 
    } 

    int inc=atoi(argv[1]); 

    if (inc <=0) { 
      printf("Expected first argument to be a 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 this is where the seg fault occurs 
      i++; 
    } 
    string[i]=0; 

    i=0; 
    while(string[i]!=0) { 
      printf("The %d char is %c\n",i,string[i]); 
      i = i + inc; 
    } 

    return 0; 
} 

運行「./prog3 5 40」正常,但運行「./prog3 5 150」會導致seg故障。

./prog3 5 150 
8 
Segmentation Fault 
+1

你的問題是? –

+0

你不能用=運算符複製字符串。使用strcpy()代替。 – Abend

+2

當你提供150作爲長度時,你試圖訪問數據越界,所以你很幸運,你會崩潰告訴你做錯了。如果第二個參數等於或大於MAX_STR_LEN,則會出現問題;如果它長於'strlen(testval)',你也會遇到問題。 150比兩者都長。 –

回答

0

這樣會更好。您需要使字符串緩衝區足夠大以容納您放入其中的所有數據。分段錯誤來自寫入不允許程序使用的內存地址。

#include <stdio.h> 
#include <stdlib.h> 
#define MAX_STR_LEN 100 

int main(int argc, char **argv) { 

    char *testval="This is a test, this is only a test. For the next sixty seconds, this will be a test of the emergency broadcasting system."; 

    if (argc<2) { 
     printf("Expected at least one argument.\n"); 
     return 1; 
    } 

    int inc=atoi(argv[1]); 

    if (inc <=0) { 
     printf("Expected first argument to be a 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 is %c\n",i,string[i]); 
     i = i + inc; 
    } 

    return 0; 
} 
相關問題