传递大参数时的Segfault

时间:2015-10-02 23:53:32

标签: c segmentation-fault

我的程序应该打印出一串文本中的每个第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;
}

跑步&#34; ./ prog3 5 40&#34;工作正常,但正在运行&#34; ./ prog3 5 150&#34;导致段错误。

./prog3 5 150
8
Segmentation Fault

1 个答案:

答案 0 :(得分: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;
}