strcpy Gives Segmentation fault - c

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.

Related

What is the issue with this C code which has a error?

It is a code written to copy one pointer to another.
ERROR is Segmentation error (core Dumped)
#include<stdio.h>
char strcp(char *,char *);
int main()
{
char *p="string",*q;
printf("%s",p);
strcp(p,q);
printf("%s",q);
return 0;
}
char strcp(char *p,char *q)
{
int i;
for(i=0;*(p+i)!='\0';i++)
*(p+i)=*(q+i);
}
char *p="string"...
strcp(p,q);
What p points to is a literal and literals are read-only. Trying to copy anything to it is forbidden (and causes a segmentation fault).
...and q is not initialized, another possible cause of the seg fault.
The problem with this algorithm is an implicit assumption it makes about pointers: char *q is not a string, it is a pointer to character. It can be treated as a string if you allocate space and place a null-terminated sequence of characters into it, but your code does not do it.
You can allocate space to q with malloc, like this:
char *p="string";
char *q=malloc(strlen(p)+1);
In addition, your version of strcpy reads null terminator from a wrong pointer, and does not null-terminate the copied string:
char strcp(char *p, char *q)
{
int i;
for(i=0;*(q+i)!='\0';i++) // <<== Fix this
*(p+i)=*(q+i);
*(p+i) = '\0'; // <<== Add this line
}
As the other answers have indicated the problem starts* with char *p="string",*q;.
The Literal "string" compiles to the equivalent:
const char foo[7] = {'s','t','r','i','n','g','\0'}; why *\0
As you might see further in you code you're trying to copy data to a const a\rray. Which is illegal.
But you're playing C, you have implicitly casted the const char foo[] to a char *p, right there during initialization.
C is not type safe because it's tightly coupled to the actual instruction on the hardware. Where types don't exist anymore, just widths. But that is for another topic.
*It's not the only flaw. I tossed in a few explanatory wiki links. Because the question shows you're a novice programmer. Keep up the work.

Segmentation fault (core dumped) in a C program [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)
Segmentation fault (core dumped) in a simple C code
(3 answers)
Closed 8 years ago.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *Change(char *str,int start,int end)
{
if(start==end || start>end){
return str;
}
else{
char temp=str[start];
str[start]=str[end];
str[end]=temp;
return(Change(str,start++,end--));
}
return str;
}
char *Reverse(char *str)
{
int length=strlen(str);
return(Change(str,0,length-1));
}
int main()
{
printf("%s\n",Reverse("program"));
return 0;
}
I am trying to write a recursive function to reverse a string,but it comes the linking error.Please help.I had tried so many times and searched in the Internet,but it can't help.
I guess the most probably place causing the problem is in function Change,but I can't solve with it.
You're passing a string literal (which is a const char*) to Reverse(), since you can't modify a string literal, your program generates a segmentation fault.
You'll either need to pass a modifiable string to Reverse():
char myStr[] = "program";
printf("%s\n",Reverse(myStr));
Or you can make a copy of the input string in Reverse():
char *Reverse(const char *str)
{
int length=strlen(str);
char* temp = malloc(length);
strcpy(temp, str);
return(Change(temp,0,length-1));
}
In that case, you'll need to free the string returned by Reverse():
char* reverseStr = Reverse("program");
printf("%s\n", reverseStr );
free(reverseStr);
Also in change(), start++ end end-- will return the value before they are incremented, you need to use either ++start or simply start+1 since you won't use those variables anymore:
return(Change(str,start+1,end-1));
Simple explanation: You can't modify a string literal. One more thing is that the statement
return(Change(temp,0,length-1));
will cause compilation error because neither temp is defined in the function Reverse nor it is globally defined.

what is the pointer error in this code?

I am trying to understand pointers and here is a program in K&R that I am trying to implement.
The program is strcpy with code from KR.
/*strcpy: copy t to s; pointer version 3*/
void strcpy(char *s, char *t){
while(*s++ = *t++)
;
}
So to implement this program, I add
#include<stdio.h>
int main(){
char *s="abc", *t="ABC" ;
strcpy(s,t);
printf("%s\n",t);
printf("%s\n", s);
return 0;
}
However I am getting segmentation error when I run it. I am sure I am missing something but not quite sure what.
Thanks!
char *s="abc", *t="ABC" ;
string literals are not modifiable, however, a char array can be modified, so change it to :
char s[] ="abc", *t="ABC" ;
Literal string values are stored in a read-only memory page; they cannot be modified.

Whats wrong with the given code

I am just learning some pointers stuff in C and I happened to learn that using the * one can dereference the pointer. So I wrote the following code to check for that.
#include<stdio.h>
#include<string.h>
char *findChar(char *s, char c){
while(*s!=c){
s++;
}
return s;
}
int main(){
char myChar='a';
const char myString[]="Hello abhishek";
char *location;
location = findChar(myString,myChar);
puts(location);
char temp = *location;
printf(temp);
}
I assume that temp should get the value pointed by the character pointer location, But this program is giving me a segmentation fault. Please clearify what I am doing wrong?
The following is incorrect:
char temp = *location;
printf(temp);
If you want to print out the char, use the following:
char temp = *location;
printf("%c\n", temp);
The first argument to printf() should be the format string.
The first argument of printf should be char* (for the format), not char.
Try printf("%c\n",temp);
By the way, to see the index of myChar in the array, you may want to print location-myString
The printf causes the segmentation fault, as printf expects a char pointer for temp and you pass a single char to it.

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