0

I keep getting seg fault and I don't know why, if someone could help me with this it would be great. I cannot find the error here............

I get all the print states up till the end of the the first four loop

i however do not get the "out" print statement,, thats where the set fault is

#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;
}
2
  • 1
    Please format the code so i becomes readable. Commented Sep 18, 2016 at 18:57
  • In for(ewm =1 ; ewm<= arg; ewm++){ int tempr = (strlen(argWords[ewm]) +1); printf("tempr: %d\n", tempr); words->numWords = words->numWords + tempo; — what is tempo? Does the code compile? And how is the structure type Words defined? Also, C arrays normally start at index 0, fo you normally use for (ewm = 0; ewm < arg; ewm++) rather than what you wrote. Commented Sep 18, 2016 at 20:39

1 Answer 1

2

arg is the number of elements in argWords, so the following code from getWords function access out of array bounds:

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

You get unpredictable behavior when accessing argWords[x]. Proper upper bound should be x < arg.

Same problem at:

 for(ewm =1 ; ewm<= arg; ewm++)   // <--- here must be ewm < arg
 {
   int tempr = (strlen(argWords[ewm]) +1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.