Why getting a "bus error" when playing with pointers? [duplicate] - c

This question already has answers here:
What is a bus error? Is it different from a segmentation fault?
(17 answers)
Closed 1 year ago.
so I was playing with pointers because I didn't know what else to do and usually, I imagine what's going on under the hood after each instruction. But I recently came against an error that I don't really understand.
char *str = "test";
printf("%c", ++*str);
Output :
zsh: bus error
Expected output was a 'u' because as far as I know, it first dereference the first address of the variable 'str' wich is a 't' than increment it right ? Or am I missing something ?
Changing the code like so is not giving me any error but why ?
printf("%c", *++str);
Thank you !

You cannot modify the data in a string literal. What you expect will work if you do:
char buf[] = "test";
char *str = buf;
putchar(++*str);
because the content of buf is writeable.

Related

Why am I receiving a segmentation fault in C when trying to alter the value of an array? What should I do to fix this? [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)
Why can I not modify a string literal in c?
(1 answer)
Closed 17 days ago.
I'm new to C as will be probably pretty obvious soon enough. I was trying to make a program which changes part of an array but I am getting a segmentation fault. I made a smaller, very simple program, (pasted below) to see if I could work out a solution to the problem in isolation, but I'm getting the same segmentation fault.
#include <cs50.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
string array[4] = {"Hello", "my", "name", "is"};
printf("%c%c%c\n", array[0][0], array[2][1], array[2][2]);
char letter = 'B';
// next line causes segmentation fault
array[0][0] = letter;
printf("%c%c%c\n", array[0][0], array[2][1], array[2][2]);
// next line would not cause fault (if program hadn't already stopped)
array[3] = "isn't";
printf("%s\n", array[3]);
}
So from this test program, I can see that it is fine for me to print chars of each string array, but if I try to edit them I get the segmentation fault. Why is this causing the fault? and what would be the correct way to achieve the same goal?
I noticed that changing the string itself is fine and does not cause a fault. ( array[3] = "isn't" )

C Segmentation Fault when trying strcpy on char *pointer [duplicate]

This question already has answers here:
C segmentation fault-char pointers
(3 answers)
Closed 8 years ago.
I'm new in learning the C-Language and I have a question to pointers.
For Example if I try this:
char *pointer;
strcpy(pointer,"Hello, World!\n");
printf(pointer);
I get this Output:
Segmentation Fault
But if I try this:
char *pointer = "Hello, World!\n");
printf(pointer);
I get this:
Hello, World!
My question is why it isn't working with strcpy.
The functions do the same overall.
What is the difference between the first sourcecode and the second?
It would be good if someone could explain what is happening in the memory, so that I can get a better view at this.
char* pointer merely gives you a variable to use to access the memory location. You've not yet allocated any memory, so when you do the strcpy you're writing to whatever random/undefined value pointer has.
You need to do something like:
char* pointer = calloc(LEN);
if (pointer)
{
strcpy(pointer, "Hello World");
printf(pointer);
free(pointer);
}
The first parameter to "strcpy" should be pointing to a usable location in memory. In your first source code, you havent initialized "pointer" to anything. You should first initialize it, for example by declaring it to be an array of characters of maximum length:
char myArray[42]; // where 42 represents the maximum capacity

manipulating a char* in c [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.
This is my program and it is seg faulting when i try to do s[0] = s[1].
I don't understand why this wouldn't work as all i am doing is taking value in s[1] and putting it in s[0].
#include<stdio.h>
void main() {
char x;
char *s="stackoverflow";
s[0] = s[1]; // it is segfaulting here
x = s[0]; //this works though
printf("this is: %s\n",s);
}
i am compiling using gcc filename.c and running it using ./a.out in ubuntu terminal.
Thank you.
When you do: char *s="stackoverflow"; then s is a pointer that points to a memory that is in the code part, so you can't change it. Because it's read-only, you're getting segmentation fault at runtime (if you used the const keyword, you would get a compilation error, which is better.. So it's recommended to use const if you don't want to make changes on strings).
If you do char s[]="stackoverflow"; then s is an array of chars that are on the stack, so you can change it.
You should not attempt to change a string literal. If you want to modify the value, make a copy using strcpy for instance.
Change declaration of variable:
char s[] = "stackoverflow";
will remove the problem you have, as variable will have storage allocated on entering the scope and initialized with the data given.

c string still works when out of boundary? [duplicate]

This question already has answers here:
Accessing an array out of bounds gives no error, why?
(18 answers)
Closed 9 years ago.
who can tell me why the code below still works? it is obvious that the str[4] is out of boundry:
#include<stdio.h>
int main(){
char str[3];
scanf("%s", str);
printf("%c\n", str[4]);
printf("%s\n", str);
return 0;
}
when it runs, enter abcdefg, it will echo the 5th char and the whole string, nothing
will be wrong, weird?
It has been declared that c/c++ doesn't do the boundary checking, while in the case above,
how should I use printf to print a c-string that the user has entered? or more generally, how to properly use a c-string that comes from users?
str[4] gives you a pointer to the memory address after the last element of your string. You can still convert this to a character, but you never know what you get and your software might crash.
Why does it work?
It doesn't "work". It might appear to be working, though; since your code (accessing an array out of bounds) invokes undefined behavior, you can get literally any result. Undefined behavior doesn't mean "it must crash".
You wrote:
when it runs, enter [abcdefg], it will echo the 5th char and the whole
string, nothing will be wrong, weird?
but I see no input reading in the code you posted:
#include<stdio.h>
int main(){
char str[3];
printf("%c\n", str[4]);
printf("%s\n", str);
return 0;
}
In any case, str[4] points to the 5-th char (byte) starting from str, so it will print any "garbage" that happens to be in that memory location when your program runs.
Accessing array items out of bounds is undefined behavior, so the exact behavior is not specified.
Just pay attention to your array bounds.

String function in c [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why do I get a segmentation fault when writing to a string?
I was writing a simple string function. The problem is: I declare a char pointer, then once I try to update a specific character, the program crashes.
I have checked some previously written string processing, I found that they modify specific characters. But when I try to run them, I get the same problem.
Sample:
stringprocess()
{
char *s;
s=" I am c programmer";
s=" but, ..... um";
*s='x'; //program crashes here...
*p="abc";
*s=*p; // this also cause crashing
........
}
Why does this happen?
s=" but, ..... um";
s points to a string literal. Trying to modify a string literal invokes undefined behaviour. Often, string literals are stored in read-only memory, then a crash is the immediate consequence of such an attempt.
You should use a char s[100] (just for example) or a malloced pointer if you want to modify the contents.

Resources