Segmentation fault using strcmp and char *arr[] - c

I am working on creating a shell and I haven't use C for a while. I have the shell initizing properly but when I try to compare the user input to an array of strings I have I get a segmentation fault. I was planning on adding casce statements in a the for loop to initiate each of the processes once they are called by the user. I haven't included those since I have been trying to figure out how to get the user input to match with a value in my string array. Under debug I was only receiving the first character of the builtins[j] value which kind of makes since since it is a pointer right. However I am stuck and could use some ideas for why this isn't returning 0 when I input "exit". Thanks
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
//This code is for creating a basic shell
void init_shell(int num, char *prompt[]){
char s1[] = "-p";
int result;
if(num>1){
result = strcmp(s1, prompt[1]);
if(result==0){
printf("%s>$", prompt[2]);
}else{
printf("308sh>$");
}
}
//printf("%s\n %s\n %s\n %d\n", prompt[0], prompt[1], prompt[2], result);
else{
printf("308sh>$");
}
}
//The infinite loop for accepting user input until it closes
int main(int argc, char *argv[]){
const char *builtins[7];
builtins[0] = "exit\n";
builtins[1] = "pid\n";
builtins[2] = "ppid\n";
builtins[3] = "cd\n";
builtins[4] = "pwd\n";
builtins[5] = "set\n";
builtins[6] = "get\n";
char usr_in[]="";
char cmp[]="";
while(1==1){
init_shell(argc, argv);//intial prompt for the shell
fgets(usr_in,100,stdin);
//Check for builtin Commands
int cmds_size = 7;
int j=0;
int res;
for(j; j<cmds_size; j++){
res=strcmp(usr_in, hold);
if(res==0){
printf("Execucting\n");
}
else{
printf("no command\n");
}
}
}
return(0);
}

The issue here is that you're writing the user's input to a buffer that isn't big enough to hold anything other than a null terminator.
char user_in[] = "";
The above line tells the C compiler that you need just enough space to store [ '\0' ], which is a single byte. The C compiler doesn't know that you may later write a 100-byte string to that buffer.
When you write to the buffer, the user's input overflows and will overwrite other values in your stack. Since the other values in your stack are pointers, what'll happen is you'll run into seg-faults, since you're writing character values into those bytes, but interpreting them as char pointers.
You are correctly limiting the size of the allowed input from the user to 100 characters, but you should make sure that your buffer is big enough to hold the value you're reading in:
char user_in[101];
for(int i = 0; i < sizeof(user_in) / sizeof(user_in[0]); i++) {
user_in[i] = 0; // Since this is allocated on the stack *in main*, this
// shouldn't be necessary
}
Here's one example of how you can rewrite your main method:
#include <stdio.h>
#include <string.h>
typedef enum { false, true } bool; // If you don't have this
// defined already
int main(int argc, char *argv[]) {
const char *builtins[7];
builtins[0] = "exit\n";
builtins[1] = "pid\n";
builtins[2] = "ppid\n";
builtins[3] = "cd\n";
builtins[4] = "pwd\n";
builtins[5] = "set\n";
builtins[6] = "get\n";
char user_in[101];
for(int i = 0; i < sizeof(user_in) / sizeof(user_in[0]); i++) {
user_in[i] = 0;
}
while(1) {
printf("Enter a command: ");
fgets(user_in, 100, stdin);
bool found = false;
for(int i = 0; i < sizeof(builtins) / sizeof(builtins[0]); i++) {
if (!strcmp(user_in, builtins[i])) {
printf("Found command %s", builtins[i]);
found = true;
break;
}
}
if (!found) {
printf("Didn't find command\n");
}
}
return 0;
}
Also, regarding your function init_shell: you're checking to see if argc is greater than 1, but that only guarantees that argv[1] is defined; it doesn't guarantee that argv[2] is defined. (Remember, argc is the size of the argv array, where the first element is the name of the program being executed). You want to make sure that argc is at least 3 before checking for the prompt flag in the way you are.
It may be overkill for your use-case, but consider using the getopt function for getting a custom prompt value from the user. See http://man7.org/linux/man-pages/man3/getopt.3.html for documentation regarding that method.

Related

Stack smashing detected in C - why does this happen?

I have the following function, which, given a string, should find the most recurrent couple of letters in it and store the result in a different string.
For example - for the string "ababa", the most recurrent couple would be "ba", and for "excxexd" it would be "ex". This is the code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
void printError(){
printf("Error: please check your input\n");
}
bool isLexicographicallyPreceding(char couple1[], char couple2[])
{
if (strcmp(couple1, couple2)>=0) return true;
return false;
}
void coupleDetector(int length, char word[], char result[])
{
char couples[length-1][2];
for (int i=0; i<length-1; i++)
{
char couple[2] = {word[i], word[i+1]};
strcpy(couples[i], couple);
}
char element[]="";
int count=0;
for (int j=0; j<length-1; j++)
{
char tempElement[2];
strcpy(tempElement,couples[j]);
int tempCount=0;
for (int p=0; p<length-1; p++)
{
if (couples[p]==tempElement) tempCount++;
}
if (tempCount>count)
{
strcpy(element, tempElement);
count=tempCount;
}
if (tempCount==count)
{
if (isLexicographicallyPreceding(tempElement,element) == true) strcpy(element, tempElement);
}
}
strcpy(result,element);
}
int main() {
//Supposed to print "ba" but instead presents "stack smashing detected".
int length=5;
char arr[] = "ababa";
char mostCommonCouple[2];
coupleDetector(length,arr,mostCommonCouple);
printf("%s", mostCommonCouple);
return 0;
}
The code compiles without errors, but for some reason does not work as intended but prints out "stack smashing detected". Why would that be? Advices would be very helpful.
Thanks.
In trying out your program, I found a few of your character arrays undersized. Character arrays (strings) need to be sized large enough to also include the null terminator value in the array. So in many locations, having a two-character array size is not sufficient and was the cause of the stack smashing. With that in mind, following is a refactored version of your program.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
void printError()
{
printf("Error: please check your input\n");
}
bool isLexicographicallyPreceding(char couple1[], char couple2[])
{
if (strcmp(couple1, couple2)>=0) return true;
return false;
}
void coupleDetector(int length, char word[], char result[])
{
char couples[length-1][3];
for (int i=0; i<length-1; i++)
{
char couple[3] = {word[i], word[i+1], '\0'};
strcpy(couples[i], couple);
}
char element[3]; /* Define the character array */
strcpy(element, ""); /* Then initialize it if need be */
int count=0;
for (int j=0; j<length-1; j++)
{
char tempElement[3];
strcpy(tempElement,couples[j]);
int tempCount=0;
for (int p=0; p<length-1; p++)
{
if (couples[p]==tempElement) tempCount++;
}
if (tempCount>count)
{
strcpy(element, tempElement);
count=tempCount;
}
if (tempCount==count)
{
if (isLexicographicallyPreceding(tempElement,element)) strcpy(element, tempElement);
}
}
strcpy(result,element);
}
int main()
{
//Supposed to print "ba" but instead presents "stack smashing detected".
int length=5;
char arr[] = "ababa";
char mostCommonCouple[3]; /* Notice size requirement to also contain the '\0' terminator */
coupleDetector(length,arr,mostCommonCouple);
printf("%s\n", mostCommonCouple);
return 0;
}
Here are some key points.
Viewing the code, most sizes for arrays was enlarged by one to accommodate storage of the null terminator.
Work fields such as "element" need to be defined to their proper size so that subsequent usage won't also result in stack smashing.
Testing out the refactored code resulted in the following terminal output.
#Vera:~/C_Programs/Console/Recurrent/bin/Release$ ./Recurrent
ba
So to reiterate, be cognizant that character arrays normally need to be defined to be large enough to contain the largest expected string plus one for the null terminator.
Give that a try and see if it meets the spirit of your project.

Why isn't isalpha working?

I'm working with C and I need to check that the user inputed second command line argument argv[1] is made up of only alphabetical charchaters and if not, to do what is inside the else loop. I used the is alpha function but when i compile and run the program no matter what my second command line argument is (alphabetical or otherwise), its always executing the "else loop". How do i fix this?
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
int a = argc;
if (a != 2)
{
return 1;
}
string b = argv [1];
int c = strlen(b);
string m;
for (int i = 0; i < c; i++)
{
if (isalpha(b[c]))
{
m = GetString();
}
else
{
printf("Please provide a valid keyword\n");
return 1;
}
}
}
Try replacing
if (isalpha(b[c]))
with
if (isalpha(b[i]))
Currently you are checking the element at the index which is the result of strlen(b) at every iteration of your loop. Because array indices are zero based in C b[strlen(b)] is referencing '\0', the null terminator.
In reference to the Keith Thompson comment below and the answer to this question you should actually be casting the value passed to isalpha to an unsigned char to ensure that undefined behaviour is not invoked.
Thus you should change your code to
if (isalpha((unsigned char)b[i]))
to ensure there is no UB
Use isalpha(b[i]) instead of isalpha(b[c])
like this:
if (isalpha(b[i]))
{
m = GetString();
}

Whats wrong with this basic shell program? it will run fine for the first few commands but results always ends in a seg fault

I have to build a simple shell program using lex and c code. The lex portion is for breaking down the input. It has been provided for me and I'm not expected to change it. I'm in the process of getting my code to run basic commands like "ls". It seems to work the first few times I run the command but eventually always seg faults. Here is the lex code provided:
%{
int _numargs = 10;
char *_args[10];
int _argcount = 0;
%}
WORD [a-zA-Z0-9\/\.-]+
SPECIAL [()><|&;*]
%%
_argcount=0;
_args[0]=NULL;
{WORD}|{SPECIAL} {
if(_argcount < _numargs-1) {
_args[_argcount++]= (char *)strdup(yytext);
_args[_argcount]= NULL;
}
}
\n return (int)_args;
[ \t]+
.
%%
char **getln() {
return (char **)yylex();
}
This is the C code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
extern char **getln();
int main() {
int i;
char **args;
int child1;
int status1;
int counter=0;
int argCount = 1;
char **array = (char **)malloc(1500 * sizeof(char *));
for (i = 0; i < 1500; ++i) {
array[i] = (char *)malloc(500);
}
strcpy(array[0],"ls\0");
array[1] = NULL;
while(1) {
args = getln();
printf("is error here?");
strcpy(array[0], args[counter]);
for(i = (counter+1); args[i] != NULL; i++) {
printf("\nRight before copying to subarray");
strcpy(array[argCount], args[i]);
argCount++;
}
array[argCount] = NULL;
if (strcmp(args[counter],"exit")==0) exit(0);
child1 = fork();
if(child1==0){
execvp(array[0], array);
printf("Unknown command, please try again.");
exit(1);
}
else{
while (wait(&status1) != child1);
}
for(i = 0; args[i] != NULL; i++) {
printf("Argument %d: %s\n argCount: %d", i, args[i], argCount);
}
argCount = 1;
counter++;
}
}
Thanks in advance for any advice. If there is some simple way to adjust the getln() function to overwrite the args array each time it is called that might be easier than what I am attempting but I have no idea how to go about that.
It seems like you have put
_argcount=0;
_args[0]=NULL;
at the top of the rules section in hopes that these statements would be executed at the beginning of yylex(). And you've noticed that they aren't executed (it keeps appending to the previous values because _argcount never goes back to 0).
The obvious thing to do is move those statements into getln() just before the yylex().
What you have now is a lexer that will ignore the string _argcount=0; in the input because it will match that pattern and there's no action to go with it. The second line is even cooler since the [0] is a character class. It makes the lexer ignore the string _args0=NULL;

Struggling with strings. What is wrong with my function?

I am trying to write a small function to trim left spaces from a string, but I cannot get it right. In this version, I get the following error:
bus error: 10
Could anyone please explain to me what I am doing wrong? I am not looking so much for an alternative piece of code, but would like to understand the errors in my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void trim_string(char *);
int main(int argc, char *argv[]) {
char *temp = " I struggle with strings in C.\n";
trim_string(temp);
printf("%s", temp);
return 0;
}
void trim_string(char *string) {
char *string_trimmed = "";
int i=0, j=0;
while (isblank(string[i])) {
i++;
}
while (string[i] != '\0') {
string_trimmed[j] = string[i];
i++;
j++;
}
string_trimmed[j] = '\0';
strcpy(string, string_trimmed);
}
I have now found a workaround solution, shown below. But I am still not very clear about what I did wrong in the first place:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_LENGTH 100
void trim_string(char [MAX_LENGTH]);
int main(int argc, char *argv[]) {
char temp[MAX_LENGTH] = " I struggle with strings in C.\n";
trim_string(temp);
printf("%s", temp);
return 0;
}
void trim_string(char string[MAX_LENGTH]) {
char string_trimmed[MAX_LENGTH];
int i=0, j=0;
while (isblank(string[i])) {
i++;
}
while (string[i] != '\0') {
string_trimmed[j] = string[i];
i++;
j++;
}
string_trimmed[j] = '\0';
printf("c\n");
strcpy(string, string_trimmed);
}
Both string and string_trimmed point to string literals, here in main:
char *temp = " I struggle with strings in C.\n";
^
|
This is a string literal
temp points to a string literal and the standard says you are not allowed to modify them.
In the function trim_string you are modifying a them which is undefined behavior of which a bus error is one possible result, although anything can happen.
string_trimmed either needs to be an array like this:
char string_trimmed[n] ;
where n is the size of your input using strlen(string) would probably make sense or dynamically allocated via malloc which you would need to free at the end of your function. The same things goes for your input from main, this would work as a substitute:
char temp[] = " I struggle with strings in C.\n";
For completeness sake, the draft C99 standard section 6.4.5 String literals paragraph 6 says (emphasis mine):
It is unspecified whether these arrays are distinct provided their elements have the
appropriate values. If the program attempts to modify such an array, the behavior is
undefined.

Realloc 2D array

I'm starting to learn C and would like input characters from a command line and sort them into an array such that the row number is the ASCII character number and the columns are the index of the character from the input. I know that this must be dynamically done via realloc and malloc but I wouldn't know how to code it up. Could someone help me with this problem?
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#define totalASCII 256
int
main(int argc, char **argv) {
int locat;
char current;
int **dRow=NULL;
dRow = malloc(totalASCII*sizeof(*dRow));
for(locat=0;scanf("%c", &current)==1;locat++) {
/* I don't know what to put here */
}
return 1;
}
Your data is so small, there's really no need to allocate it from the heap. Just use an array:
struct { char character; int input_index; } input_data[totalASCII];
On a typical 32-bit system, this will use about 256 * 8 or 2 KB of memory, which really isn't all that much.
Then the storing would be:
for(locat = 0; scanf("%c", &current) == 1; locat++)
{
input_data[locat].character = current;
input_data[locat].input_index = locat;
}
Disclaimer: haven't compiled and run the code.
Try something like this:
int prev_size = 1;
dRow = calloc(totalASCII, sizeof(*dRow)); //use calloc
for(locat=0;scanf("%c", &current)==1;locat++) {
if(dRow[current]) {
prev_size=0;
//try to find how much is already allocated
while(dRow[current][prev_size] != -1)
prev_size++;
dRow[current] = realloc(sizeof(int) * (prev_size+1));
}
else {
prev_size = 1;
dRow[current] = malloc(sizeof(int) * (prev_size+1));
}
dRow[current][prev_size-1] = locat;
dRow[current][prev_size-1] = -1; //end identifier
}
The complexity here is to find the previous allocated size. As there is no other structure/data structure to store this info, this sample code tries to iterate over the array and find -1 which is assumed as end marker.

Resources