Segmentation fault when using strcpy() - c

We added print statements to check where the segmentation fault was happening. It fails at strcpy(command, token);
How can we store that part into command? Also is there a way to check for the null character at the end of token? Does strtok() have a null character at the end when used?
int main(int argc, char **argv)
{
char *command, *flag, *pathname, *linkname;
struct stat st = {0};
char cmd[200];
char *token; //Pointer
int counter = 1; //Counter variable
FILE *fp;
char mode2[] = "0750"; //To set the permission of a file/path
long j;
char mode[] = "0640"; //To set the permission of a file/path
long i;
fgets(cmd, 200, stdin);
printf("print for cmd: %s\n", cmd);
//User input is tokenized to determine the proper commands are entered and executed
token = strtok(cmd, " "); //Input is tokenized by white spaces.
printf("token: %s\n", token);
strcpy(command, token);
printf("print for command: %s\n", command);
if(token == NULL)
{
printf("Error with command input.\n");
exit(EXIT_FAILURE);
}

You never assign a value to command, much less allocate space for it to point to.

You need to initialize you *command variable before assigning a value to it with strcpy(). The segmentation fault will happen if you try to assign a value to a NULL pointer.
A correct use of strcpy() would be like this:
char *str = malloc(3 * sizeof(char));
char sentence[3] = "Hi\0";
strcpy(str, sentence);
printf("%s\n", str);

Related

Using char pointer in a function, get seg fault whenever trying to access first char of char pointer

I am writing a program where I take text from a file and converting it into card hands for later evaluation.
This code takes in a line from a text file and parses the line by whitespace. Each time there is a whitespace, cardVal is updated with new value. When I try to access the first char of cardVal, cardVal[0], I get a segmentation fault in the function makeCard. However when printing cardVal[0] before passing to the function it gives the correct value. So my question is how can I access the a single char of a char pointer in the function makeCard. Any help is greatly appreciated.
My code is:
#include <stdio.h>
#include "poker.h"
#include <string.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
FILE *fp;
unsigned long len = 0;
unsigned long read;
char *line = NULL;
char * cardVal;
fp = fopen(argv[1], "r");
if(fp != NULL)
{ //checks if files open
while((read = getline(&line, &len, fp)) != -1)
{ //gets a line
cardVal = strtok(line, " "); //parses line
cardVal = line;
while(cardVal != NULL)
{ //parses line until NULL
printf("%c\n", cardVal[0]); //prints 1st char successfully
cardVal = strtok(NULL, " ");
}
}
}
void makeCard(char * buff)
{
printf("%s\n", buff[0]); //!!!!SEG FAULT HERE!!!!
}
}
printf("%s\n", buff[0]); //seg fault here
"%s" expects a char* as argument, but you pass a char. Use "%c" to print single chars.

strcpy giving me segmentation fault

I have code which is giving me a segmentation fault. I debugged it and and the error occurred when the strcpy executed. The code is attempting to extract data from a text file and store it into an array of structs. I plan to use strcpy to store the store the text file's data into the structs. Any idea why this is occurring?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int input( char *s, int length);
void main(){
char *tok;
char *buffer;
size_t bufsize = 32;
size_t characters;
FILE *f;
char *file_name;
char line[255];
int currentRoom;
int count = 0;
typedef struct {
char room_n;
char description[100];
char room_north;
char room_south;
char room_west;
char room_east;
} room;
//Creating an array of structs
room record[1000];
while(1){
buffer = (char *)malloc(bufsize * sizeof(char));
if(buffer == NULL){
perror("Unable to allocate buffer");
exit(1);
}
printf("Enter a command: ");
characters = getline(&buffer, &bufsize, stdin);
if(strcmp(buffer,"exit\n") == 0){
printf("Exiting...\n");
exit(1);
}
tok = strtok(buffer, " \n"); // Tokenize input
printf("%s is the token \n", tok);
if (strcmp(tok,"loaddungeon") == 0){
file_name = strtok(NULL, "\n");
printf("file name : %s \n", file_name);
f = fopen(file_name,"r");
while (fgets(line, sizeof(line), f) != NULL)
{
char val1[128];
char val2[128];
char val3[128];
char val4[128];
char val5[128];
char val6[128];
strcpy(val1, strtok(line, "$"));
strcpy(val2, strtok(NULL, "$"));
strcpy(val3, strtok(NULL, " "));
strcpy(val4, strtok(NULL, " "));
strcpy(val5, strtok(NULL, " "));
strcpy(val6, strtok(NULL, " "));
//Segmentation fault error occurs here
strcpy(record[count].room_n, val1);
Definition of strcpy() is:
char *strcpy(char *dest, const char *src)
where-
dest -- This is the pointer to the destination array where the
content is to be copied.
src -- This is the string to be copied.
In your code arguments passed to strcpy() is char and char * :
strcpy(record[count].room_n, val1);
As defined in the structure:
typedef struct {
char room_n; //room_n declared as 'char'
char description[100];
char room_north;
char room_south;
char room_west;
char room_east;
} room;
Suggestion:
Allocate memory for room_n to point to. Change the declaration to
char room_n[128];

Segfault in parsing char* into tokens

I'm trying to parse a string around an arbitrary index. In my simplest test program I could come up with I have an input string I read the input into and then do memcpy to parse the string.
For testing this I am typing in "this text" as input. readInput is a function where I just have it calling getline(&input, &size, stdnin) and return the input pointer.
int main(){
char *input;
input = readInput();
int parseAround = 4;
char *token1;
char *token2;
memcpy(token1, inputBuffer, 4);
printf("token: %s\n", token1); //prints "this"
memcpy(token1, inputBuffer + (parseAround+1), 4);
//when changed to memcpy(token2,...); segfaults
printf("token: %s\n", token1); //prints "text"
free(input);
return 0;
}
However when I change the second memcpy to use token2 rather than token1, I get a segmentation fault. Why is this?
You most likely need to allocate memory for token1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char *input = NULL;
size_t len = 0;
ssize_t read;
/* Read in the line "Hello world" */
read = getline(&input, &len, stdin);
printf("Retrieved line of length %zu :\n", read);
printf("%s", input);
/* Allocate memory for both parts of the string */
char *token1 = malloc((read+1) * sizeof(char *));
char *token2 = malloc((read+1) * sizeof(char *));
memcpy(token1, input, 6);
printf("token: %s\n", token1); //prints "Hello"
memcpy(token2, (input+6), 5);
printf("token: %s\n", token2); //prints "world"
free(input);
return 0;
}
Read in the line, allocate memory for each string part, and then copy the part you want into your s

segmentation fault when manipulating strings?

this peace of code summarizes the problem that I have.i want to copy a file from a source to a specified destination which i'm allowed to change it's name it's a function that's integrated in an application i'm trying to create that manages files
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void concatenate_string(char *original, char *add)
{
while(*original!='\0')
original++;
while(*add!='\0')
{
*original = *add;
add++;
original++;
}
*original = '\0';
}
int main(int argc,char *argv[])
{
char *nom;
char *path;
printf("entrer a name \n");
scanf("%s",nom);
printf("entrer a pathh \n");
scanf("%s",pathh);
char *dest=(char*)malloc(strlen(nomm)+46+1);
strcat(dest,"/home/ridaamine/Desktop/app/application/Files/");
strcat(dest,nom);
char *comand=(char*)malloc(strlen(name)+8+strlen(path)+1);
strcat(comand,"cp -via ");
strcat(comand,path);
strcat(comand," ");
strcat(comand,name);
system(comand);
}
You didn't initialize nom
scanf("%s",nom);
either
nom = malloc(SOME_SIZE);
and then, let's say SOME_SIZE == 100
scanf("%99s", nom);
or
char nom[SOME_SIZE];
and then, also let's say SOME_SIZE == 100
scanf("%99s", nom);
and of course the same applies to path.
The second solution is better because it's faster not that much and you don't need to free(nom) after using it. The second case could be needed in the rare case where the size of the string is so large (> 8M) it would overflow the stack.
And as Weather Vane points out strcat has a problem too you should use strcpy the first time
strcat(dest,"/home/ridaamine/Desktop/app/application/Files/");
strcat(dest,nom);
shoul be
strcpy(dest,"/home/ridaamine/Desktop/app/application/Files/");
strcat(dest,nom);
and clearly this time, the same applies to command.
Finally you have a space that you didn't count in
malloc(strlen(dest) + 8 + strlen(path) + 1 + 1 /* space " " */)
Tip: you don't need to cast malloc so don't, it could hide a potential bug. And always check that malloc didn't return NULL, before dereferencing the pointer.
You should call free after you are done too, this is your own code fixed
int main(int argc,char *argv[])
{
char nom[100];
char path[100];
char _path[] = "/home/ridaamine/Desktop/app/application/Files/";
char cp[] = "cp -via ";
char space[] = " ";
printf("entrer a name \n");
scanf("%99s", nom);
printf("entrer a path \n");
scanf("%99s", path);
char *dest = malloc(strlen(nom) + strlen(_path) + 1);
if (dest == NULL)
{
printf("no more memory left.\n");
return -1;
}
strcpy(dest, _path);
strcat(dest, nom);
char *comand = malloc(strlen(dest) + strlen(cp) + strlen(space) + strlen(path) + 1);
if (command == NULL)
{
free(dest);
printf("no more memory left.\n");
return -1;
}
strcpy(comand, cp);
strcat(comand, path);
strcat(comand, space);
strcat(comand, dest);
free(dest);
system(comand);
free(command);
return 0; // always return from main
}
The first strcat() must in each case be changed to strcpy() because the strings have not been initialised to the empty string. And the first string dest will certainly be too short.
char *dest=(char*)malloc(strlen(nomm)+46+1); // this is too short
strcpy(dest,"/home/ridaamine/Desktop/app/application/Files/");
strcat(dest,nom);
char *comand=(char*)malloc(strlen(name)+8+strlen(path)+1);
strcpy(comand,"cp -via ");
strcat(comand,path);
strcat(comand," ");

Getting Segmentation fault (core dumped)

So i am trying to read lines and then split them in two with strtok . So if i would read "nice dog" it will first print what i read and then will print using the strtok commands "nice" and "dog" on the next line . But after second input i got Segmentation fault .Also , what does free(buf) do ? I've seen that the error is at this line : "strcpy(name, strtok(NULL, " "));" This is the code :
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *buf;
char command[32];
char name[32];
while((buf = readline("\n"))!=NULL)
{
if (strcmp(buf,"exit")==0)
break;
printf("%s\n",buf);
strcpy(command, strtok(buf, " "));
printf("%s\n", command);
strcpy(name, strtok(NULL, " "));
printf("%s\n", name);
if(buf[0]!=NULL)
add_history(buf);
}
free(buf);
return 0;
}
You must check the result of strtok if it's NULL meaning that no tokens where found you will get segmentation fault
char *pointer;
pointer = strtok(buf, " ");
if (pointer != NULL)
strcpy(command, pointer);
also, readline allocates new memory on every call so you should free inside the while loop.
Fix it this way
#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>
#include <readline/history.h>
int main()
{
char *buf;
char command[32];
char name[32];
while((buf = readline("\n"))!=NULL)
{
char *pointer;
if (strcmp(buf,"exit")==0)
break;
printf("%s\n",buf);
pointer = strtok(buf, " ");
if (pointer != NULL)
{
strcpy(command, pointer);
/* Don't print poitner otherwise since it is unintialized */
printf("%s\n", pointer);
}
/* subsequent calls to strtok must have first argument NULL */
pointer = strtok(NULL, " ");
if (pointer != NULL)
{
strcpy(name, pointer);
printf("%s\n", pointer);
}
if (buf != NULL) // this is never FALSE because of the while condition
add_history(buf);
free(buf);
}
return 0;
}
you also have to make sure that command and name will be big enough to fit the resulting stirng.

Resources