-1

in the following code, I ran into a problem where I had a string from getString method then it was fine until I entered the loop, then I lost the string. I don't know why I lost the sting it should be within the stack.

int main(int argc, char *argv[1]){
    char * str;
    getString(str, 100000);
    char * ID[100];
    int num[100];
    for(int i =0 ; i < 100; i ++){
        num[i]=0;
    }
    int j = 0; 
    for(int i =0; i < sizeof(str);i++){
        if( str[i] == '<'){
            char * strPoint = (str+i+1);
            int ln = findLenth(strPoint);
            char * strCom = malloc(ln*sizeof(char));
            memcpy(strCom, str, ln);
            int r = tag(ID, strCom, &j);
            if(r != -1){
                num[r]++;
            }
        }
    }
    for(int r = 0; r <j; r++){
        printf("%s     %d\n", ID[r], num[r]);
        
    }
    freeMemory(ID, j);
    return EXIT_SUCCESS;
}

void getString(char* str, int i){
    fgets (str, i, stdin);
}

1 Answers1

1

First, str is uninitialized. There's no telling what it points to. You'll need to allocate some space with malloc or something and initialize str with that.

Second, your loop uses sizeof(str). While this is legal even with str uninitialized, it will not give you the length you are looking for. It will give you the size of the pointer, not what it points to. It would probably work better to call strlen(str).

Fred Larson
  • 60,987
  • 18
  • 112
  • 174