C程序中的分段错误(使用结构)

时间:2016-09-18 18:50:18

标签: c

我不断遇到段错,我不知道为什么,如果有人可以帮助我,那就太好了。我在这里找不到错误............

我得到所有打印状态直到前四个循环结束

然而,我没有得到" out" print语句,那就是设置错误的地方

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

void getWords(int arg, char** argWords, Words* words);

void getWords(int arg, char** argWords, Words* words)
{
    printf("In Method\n");

    int ewm=1;
    for(ewm =1 ; ewm<= arg; ewm++){
        int tempr = (strlen(argWords[ewm]) +1);
        printf("tempr: %d\n", tempr);
        words->numWords = words->numWords + tempo;
        printf("numWords: %d\n", words->numWords);
        printf("in\n");
    }


    printf("out\n");
    printf("%d\n", words->numWords);
    int x = 1;
    int y = 0;

    printf("four loop\n");
    for(x= 1; x<=arg; x++){
        printf("SIZE: %d\n", (strlen(argWords[x] )+1));
        char* temp = malloc(strlen(argWords[x])+1);
        printf("%s\n", argWords[x]);
    }
}

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

    if(argc == 0){
        printf("Please input a value/n");
        return 1;
    }

    Words *currWords = malloc(sizeof(Words));
    printf("Mem located\n");

    getWords(argc, argv, currWords);

    return 0;
}

1 个答案:

答案 0 :(得分:2)

argargWords中元素的数量,因此来自getWords的以下代码可以访问数组范围:

 for(x= 1; x<=arg; x++)
 {
   printf("SIZE: %d\n", (strlen(argWords[x] )+1));  // <---
   char* temp = malloc(strlen(argWords[x])+1);      // <--- 

访问argWords[x]时会出现无法预测的行为。正确的上限应为x < arg

同样的问题:

 for(ewm =1 ; ewm<= arg; ewm++)   // <--- here must be ewm < arg
 {
   int tempr = (strlen(argWords[ewm]) +1)