Segmentation Fault with Direct Memory Access [duplicate] - c

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 8 years ago.
The following code results in a seg fault, when running in GDB it appears when the memory is changed to decrease the character by 32.
#include <stdio.h>
char *upper(char *);
int main(void) {
char *my_word = "hello";
printf("Upper: %s\n", upper(my_word));
return 0;
}
char *upper(char *string) {
while(*string != '\0') {
*string -= 32;
string++;
}
return string;
}

When you use string++ at the end it will point to \0.
char *upper(char *string) {
while(*string != '\0') {
*string -= 32;
string++; // don't use this method here
}
return string; // it will return the address of \0
}
while returning it will return the address of \0. so it wont print anything.
Try the following changes-
#include <stdio.h>
#include<string.h>
char *upper(char *);
int main(void) {
char my_word[] = "hello";
printf("Upper: %s\n", upper(my_word));
return 0;
}
char *upper(char *string) {
int i;
for(i=0;string[i];i++)
string[i] -=32;
return string;
}

Related

replace certain char with another char in c

I want to search my char-array for a certain char and replace it with another one. By executing the following code I get this error:
Process finished with exit code 138 (interrupted by signal 10: SIGBUS)
#include <stdio.h>
char replaceCharWithChar(char *string, char toReplace, char replacement) {
while(*string != '\0') {
if(*string == toReplace) {
*string = replacement;
}
string++;
}
return *string;
}
int main() {
printf("%s:", replaceCharWithChar("Hello", 'H', 'T');
return 0;
}
There are multiple errors. First replaceCharWithChar returns a char, but your printf string expects a char*. Also, you are modifiying a pointer to a string literal which is undefined behaviour.
To fix your issue, fix the type error and return the original string pointer (or nothing, or the number of character replaced). And don't use a string literal, use a char array instead:
#include <stdio.h>
char replaceCharWithChar(char *string, char toReplace, char replacement) {
char* string_beginning = string; //Store the pointer to the beginning of the string
while(*string != '\0') {
if(*string == toReplace) {
*string = replacement;
}
string++;
}
return string_beginning;
}
int main() {
char string[] = "Hello";
printf("%s:", replaceCharWithChar(string, 'H', 'T');
return 0;
}

exception in for loop? [duplicate]

This question already has answers here:
EXC_BAD_ACCESS when using strcpy()?
(3 answers)
Why can I not modify a string literal in c?
(1 answer)
Closed 2 years ago.
Why my code returns:
Exception: EXC_BAD_ACCESS (code=2, address=0x10d637fa2)
in the first time it enters the for loops?
void unAnnoyWord(char *str) {
char *out = str, mostAnnoying = 'a';
do
{
if (*str != mostAnnoying)
{
*out = *str;
}
} while (*str++);
}
char *str = "hakuna matata";
unAnnoyWord(str);
Perhaps this is what you want:
#include <stdio.h>
void unAnnoyWord(char *str) {
char *out = str, mostAnnoying = 'a';
do {
if (*str != mostAnnoying) {
*out++ = *str;
}
} while (*str++);
}
void main() {
char str[] = "hakuna matata";
char *sstr = str;
printf("%s\n",sstr);
unAnnoyWord(str);
printf("%s\n",sstr);
}
Resulting in:
hakuna matata
hkun mtt

Odd printf behaviour [duplicate]

This question already has answers here:
How to access a local variable from a different function using pointers?
(10 answers)
Returning an array using C
(8 answers)
Closed 3 years ago.
I have implemented my own strchr() function in C.
When calling the function and saving the output into a pointer I go ahead and print the stream of chars and the result looks fine. However, after calling a printf(), my stream of chars gets cut off for some reason. Does anyone understand why?
Here is my code:
#include <stdio.h>
#include <string.h>
char *mon_strchr(const char *chaine, int car)
{
int j = 0, i;
char *pbuff, buff[256];
pbuff = buff;
for (i = 0; chaine[i] != '\0'; i++)
{
if ((int)chaine[i] == car)
break;
i++;
}
for (i; chaine[i] != '\0'; i++)
{
buff[j] = chaine[i];
j++;
}
return pbuff;
}
int main()
{
const char str[] = "http://www.tutorialspoint.com";
const char ch = '.';
char *ret;
ret = mon_strchr(str, ch);
printf("%s\n", ret);
printf("String after |%c| is\n", ch);
printf("%s\n", ret);
return (0);
}
And this is the output:
.tutorialspoint.com
String after |.| is
.tutoria

compiler does not allow me to edit the passed string [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 5 years ago.
I looked around and I could not find a solution of my problems in other question. For some reason, then I get segmentation fault when I run my program and it seems to be because i am changing the give string. I tried passing a pointer to a char pointer and edit that, but to no avail.
what I get:
before: juanpablo
Segmentation fault (core dumped)
My code:
void rm_char(char* word, int pos){
printf("before: %s\n", word);
int len = strlen(word);
int i;
i = pos;
while(word[i+1] != '\0'){
word[i] = word[i+1];
i++;
}
word[i] = '\0';
printf("after: %s\n", word);
}
int main(void){
rm_char("juanpablo", 2);
}
From the C Standard (6.4.5 String literals)
7 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.
To escape the error you could call the function like
char s[] = "juanpablo";
rm_char( s, 2 );
Take into account that it is better to use type size_t instead of the type int for the second parameter and the variable len declared like
int len = strlen(word);
is not used in the function.
The function should be declared like
char * rm_char(char* word, size_t pos);
Here is a demonstrative program
#include <stdio.h>
#include <string.h>
char * rm_char(char *word, size_t pos)
{
size_t n = strlen( word );
if ( pos < n )
{
//memmove( word + pos, word + pos + 1, n - pos );
do
{
word[pos] = word[pos+1];
} while ( word[pos++] );
}
return word;
}
int main(void)
{
char word[] = "juanpablo";
puts( word );
puts( rm_char( word, 2 ) );
return 0;
}
Its output is
juanpablo
junpablo

passing a char* as argument breaks program whereas char[] does not [duplicate]

This question already has answers here:
What is the difference between char s[] and char *s?
(14 answers)
Definitive List of Common Reasons for Segmentation Faults
(1 answer)
Closed 5 years ago.
I have the following code to split strings by tokens:
char **strToWordArray(char *str, const char *delimiter)
{
char **words;
int nwords = 1;
words = malloc(sizeof(*words) * (nwords + 1));
int w = 0;
int len = strlen(delimiter);
words[w++] = str;
while (*str)
{
if (strncmp(str, delimiter, len) == 0)
{
for (int i = 0; i < len; i++)
{
*(str++) = 0;
}
if (*str != 0) {
nwords++;
char **tmp = realloc(words, sizeof(*words) * (nwords + 1));
words = tmp;
words[w++] = str;
} else {
str--;
}
}
str++;
}
words[w] = NULL;
return words;
}
If I do this:
char str[] = "abc/def/foo/bar";
char **words=strToWordArray(str,"/");
then the program works just fine but if I do this:
char *str = "abc/def/foo/bar";
char **words=strToWordArray(str,"/");
then I get a segmentation fault.
Why is that? The program expects a char* as an argument then why does a char* argument crash the program?
Because the function contains:
*(str++) = 0;
which modifies the string that was passed to it. When you do:
char *str = "abc/def/foo/bar";
str points to a read-only string literal. See the section titled Attempting to modify a string literal in this question:
Definitive List of Common Reasons for Segmentation Faults

Resources