Segmentation faults in DAG Program - c

struct da
{
int ptr,left,right;
char label;
}dag[25];
int ptr,l,j,change,n=0,i=0,state=1,x,y,k;
char store,*input1,input[25],var;
l=strlen(input1); //i'm Getting Segmentaion Fault here
The Complete Program is here
http://bmohanrajcse.blogspot.com/2018/01/9-construction-of-dag.html
I didn't Know where & what to correct ,Please help

input is uninitialized. strlen(NULL) will segfault. Try this:
char *input = "";

Related

strcpy Gives Segmentation fault

The following is a recursive function that is supposed to turn an integer into a string
char* int_to_word(int word_int){
static char new[2];
char alphabet[26]={"abcdefghijklmnopqrstuvwxyz"};
new[0]=alphabet[word_int%27-1];
//new[1]='\0';
if(word_int/27==0){
return new;
}
static char *word;
strcpy(word,strcat(int_to_word(word_int/27),new));
return word;
}
I'm getting a segmentation fault with the line strcpy(word,strcat(int_to_word(word_int/27),new)); when word_int > 26. To my knowledge, there's no reason it shouldn't work. My best guess is that I somehow neeed to allocate word before copying into it, but changing the initializer to static char *word=(*char)malloc(100) did not help.

Struct Array Segmentation Fault

I keep running into a problem with reading values of a struct array, where I keep getting a segmentation fault. Here is the code:
int main()
{
/* Get PATH Environment Variable */
char *pathv[MAX_PATHS];
char cmd_line[MAX_ARGS];
struct command_t cmd[3]; //THIS IS THE STRUCT ARRAY
size_t len = 0;
/* Parse The Path */
ParsePath(pathv);
while(1) {
/* Print Continuous Prompt */
PrintPrompt();
/* Read Command Line & Parse It */
ReadCommand(cmd_line);
ParseCommand(cmd_line, cmd); //PASSING IT TO THIS METHOD
}
return 0;
}
int ParseCommand(char *buffer, struct command_t *cmd)
{
char *name = "Test";
cmd[0].name; //IF THIS IS COMMENTED OUT AND THE OTHER LINE AS WELL, PROGRAM RUNS
printf("%s\n", cmd[0].name); //FINE....THESE TWO LINES CAUSE SEG. FAULT
}
struct command_t {
char *name;
int argc;
char *argv[MAX_ARGS];
};
What am I doing wrong? Your help is greatly appreciated.
You never initialize cmd nor write any data. Accessed uninitialized data is undefined behavior in C so yes it is valid to crash. You need to write something into cmd[0].name before reading from it.
In C, when you declare a variable without assigning a value to it doesn't mean it is empty. It may point to memory garbage from stuff that was ran previously.
Your attempt to printf() whats in cmd[0].name without initializing it can be catastrophic.
You should initialize each variable in your struct before trying to access its value, or at least zero-fill everything in order to make it safe to read:
memset(cmd, 0, sizeof(*cmd) * 3);

Segmentation fault (core dumped) in a simple C code

I am new in C. I am referring to the book "The C Programming Language" by Brian W Kernighian and Dennis Ritchie.
There is a code for pointer increment and assignment given in the book as follows.
#include<stdio.h>
int main()
{
char *s = "Goal";
char *t = "Home";
while(*s++ = *t++) printf(*s);
return 0;
}
The code is saved and compiled using the command
gcc ptr.c -o ptr -std=c99
Now on running the code by running command
./ptr
I get the following error
Segmentation fault (core dumped)
The error seems to be inside the while loop condition.
But the code is exactly as given in the book.
What am I missing?
s and t are both string literals, and you can't modify a string literal. But this piece of code
*s++ = *t++
will modify s, which causes segmentation fault.
To fix it, use a char array. I also modified the printf part to make it legal.
#include<stdio.h>
int main()
{
char arr[] = "Goal";
char *s = arr;
char *t = "Home";
while(*s++ = *t++)
;
printf("%s\n", arr);
return 0;
}
However, I think this program is better done using an individual function to copy the string, the program will look clearer.
#include<stdio.h>
void my_strcpy(char *s, char *t);
int main()
{
char s[] = "Goal";
char *t = "Home";
my_strcpy(s, t);
printf("%s\n", s);
return 0;
}
void my_strcpy(char *s, char *t)
{
while(*s++ = *t++)
;
}
The problem is that printf expects the first parameter to be a char *, that is, something that points to a character, or the address of a character. When you say printf(*s) you're passing it an actual character, i.e. a number from 0 to 255 or -128 to 127, and the program is going to treat that number as an address, which isn't going to be a valid address on your system.
When ever we say *s = "hello" , s is pointing to an address which is present in text segment("hello" goes into text segment). So obviously changing the value of text segment results in SEGV termination.
And for s[] = "hello" if we do *s++, we are incrementing (modifying) the base address so we got "lvalue required as increment operand" error.

segmentation fault run time error [duplicate]

This question already has answers here:
Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?
(19 answers)
Closed 9 years ago.
i have written a code . this looks as follows .
#include<stdio.h>
#include<string.h>
int do_print2(char *q[]);
int main()
{
char *p[]={"pointervaule","NAM", "JAM", "CALM"};
do_print2(p);
return 1;
}
int do_print2(char *p[])
{
printf("this is print1 char *p \n");
strcat(p[0],"added");
printf("%s\n", (p[0]));
return 1;
}
after compilation, i am trying to run it, i am getting segmentation fault. help me in learning what is the reason for that error. thank in advance.
In your code: strcat(p[0],"added"); try to write on read only memory that is illegal in C. Because p[0] points to a constant string.
Not p is pointer to char array, but not 2-dimensional char array.
Read: Difference between char* str[] and char str[][] and how both stores in memory? an answer with diagrams and code examples, to understand it better.
The OS says that the C strings are in the read section of the object (i.e. protected from writing).
Due to historical reasons "bla bla" is really a const char * const data type, but is allowed to get away in the C compilers eyes some teenage interdependencies. But the headmaster (OS) is less forgiving and expels the running of such code in the corridors. (how many metaphors in that statement).
You can't write to read only memory, better way to do this:
#include<stdio.h>
#include<string.h>
int do_print2(char q[][20]);
int main()
{
char p[4][20] = {{0}, {0}, {0}, {0}};
strcat(p[0],"pointervaule");
strcat(p[1],"NAM");
strcat(p[2],"JAM");
strcat(p[3],"CALM");
do_print2(p);
return 1;
}
int do_print2(char p[][20])
{
printf("this is print1 char *p \n");
strcat(p[0],"added");
printf("%s\n", (p[0]));
return 1;
}

returning pointer to a character array from a function in a different file other than main

I can't return a pointer to a character array from a different file other than the main function. It always says "segmentation fault". But if I write the function in the same file as main, There is no problem.
/* this is in mainfunc.c file*/
int main()
{
char ch[5]={'a','b','c','d','\0'};
char *res=retchararray(ch);
printf("%s\n",res);/*I get segmentation fault only when I use this printf*/
}
/* this function is in other file newfile.c */
char *retchararray( char *p){
char *str;
str=p;
unsigned int len=strlen(p);
*(str+len)='e';
*(str+len+1)='\0';
return str;
}
I use netbeans on Mac OS to do C Programming.
Can some please tell me what is the problem? Or Am I doing some mistake here?
The function retchararray overflows your array. You use more memory than you have reserved.
This happens in *(str+len+1) = '\0' and causes the segfault.

Resources