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

C PROGRAMMING QUESTION, please answer with code example In the code below, I am

ID: 3902868 • Letter: C

Question

C PROGRAMMING QUESTION, please answer with code example

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


Given below is the fixed code.
When there is no second token, the call to strtok() returns NULL and you assigned that to value. You will not be able to access index [0] on NULL in that case and it causes segmentation fault.

Please do rate the answer if it helped. thank you.

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

int tokenize(char *insertion){
int x = -1;
char *search = " ";
char *token;
char instruction[20] = "";
char value[20] = "";

token= strtok(insertion,search);
strcpy(instruction, token);


token = strtok(NULL,search);
if(token != NULL)
strcpy(value, token);

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;

}