Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C PROGRAMMING QUESTION In the code below, I am having trouble with my tokenize f

ID: 3902802 • Letter: C

Question

C PROGRAMMING QUESTION

In the code below, I am having trouble with my tokenize function. I need to return 2 if the input is exactly one string which is "pop" , return 1 if there is exactly two inputs and the first one is "push", and return -1 otherwise. I keep getting Segmentation fault(core dumped), when there is not exactly two inputs. What am I doing wrong?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "prog1_2.c"

int tokenize(char *insertion){
   int x = -1;  
   char *search = " ";
   char *instruction = strtok(insertion,search);
   char *value = strtok(NULL,search);
   if(strcmp(instruction,"pop") == 0 && value[0] == ''){
       return x = 2;
   }
      

  
   if(strcmp(instruction,"push") == 0 && strlen(value) >= 1){
       x = 1;
}
  
   return x;
}

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

   printf("Assignment #1-3, Anthony Reese, areese@sdsu.edu ");
   if(argc != 2){
       printf(" This program expects a single command line argument ");
       return-1;
   }
   char *p;
   int num;
   long conv = strtol(argv[1], &p, 10);
   num = conv;
   while(num!=0){
       char input[256];
  
       printf(">");
       scanf (" %[^ ]s",input);
       printf("%d ",tokenize(input));
       num--;  
   }
return 0;
  
}

Explanation / Answer

The solution will be that you can check whether the char array contains pop or push first if not then return -1 at the start of function before invoking strtok and other functions.