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 is this string reversal C code causing a segmentation fault? [duplicate]
(8 answers)
Closed 4 years ago.
I'm attempting to remove duplicate characters from a string without using any additional buffer. The code works when I declare a single variable like this
char s[] = "aaabbb";
but not when I'm attempting to loop through a few test cases.
#include <stdio.h>
#include <string.h>
/* Design an algorithm and write code to remove the duplicate characters in a string
without using any additional buffer. NOTE: One or two additional variables are fine.
An extra copy of the array is not. */
void removeDuplicates(char s[]) {
// attempts to modify array in place without extra buffer
}
int main() {
char *s[4] = {"aaaa", "abcd", "ababab", "aaabbb"};
int i;
for (i = 0; i < 6; i++) {
removeDuplicates(s[i]);
}
return 0;
}
This returns Bus error: 10 because it's attempting to modify the string literal "aaaa" but I'm not sure how to overcome this while maintaining a nice setup for the test cases.
The s[i] are pointing to string literals, you need a 2-dimensinal char array like this:
char s[][7] = {"aaaa", "abcd", "ababab", "aaabbb"}
Also note that for a string of length n you need at least n+1 spaces because of the '\0'-termination."aaabbb"` has length 6, so it need at least 7 spaces.
Then you can do
int main() {
char s[][7] = {"aaaa", "abcd", "ababab", "aaabbb"};
size_t i;
for (i = 0; i < sizeof s / sizeof s[0]; i++) {
removeDuplicates(s[i]);
}
return 0;
}
Related
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)
What is the difference between char s[] and char *s?
(14 answers)
Closed 9 months ago.
I want to create void function that will change existing dynamic (or static) array. How this can be implemented in C and C++? How to properly pass arguments to such functions? For example i want to reverse char array
//function that reverse the string
void reverseString(char* str)
{
char t;
int i, j;
for (j = 0; str[j] != '\0'; j++)
{
}
j -= 1;
for (int i = 0; i < j; i++, j--)
{
t = str[i];
str[i] = str[j];
str[j] = t;
}
}
int main()
{
char* name = "Ani?321";
reverseString2(&name);
printf("%s", name);
}
running this code: Exception thrown at 0x796028BC (ucrtbased.dll) in Strings.exe: 0xC0000005: Access violation reading location 0x00E87B51.
When i changing function parameter from char* to char** -> Run-Time Check Failure #2 - Stack around the variable 'str' was corrupted. (pointing to the closing curly bracket of the main function)
You have two major problems:
Your pointer name is pointing to a literal string. Such strings can't be modified, and any attempt to do so leads to undefined behavior. You solve this issue by using an array instead:
char name[] = "Ani?321";
The second problem is that you pass a pointer to the pointer to your function. The type of &name (in your current code) is char **, which is not the correct type and definitely not the correct pointer. You should pass plain name as argument (which will also work when you solve the first problem).
Well, you have declared a string literal which you can't modify. Declare it like this instead char name[] = "Ani?321";
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 2 years ago.
my main function needs to collect array size from user and fill it with strings, to then send out to functions - my main appears to crash after recieving a single string - I believe the error is due to temporary_string - when it does work I get no indication the arrays actually enter the function and the output is the same as the input - I don't know why.
int main() {
int n = 0, rule = 0;
char* temporary_string="";
printNumStringsInputMessage();
scanf("%d", &n);
printStringsInputMessage(n);
char** arr_of_strings= malloc(n * sizeof(char*));
for (int l = 0; l < n; l++)
{
scanf("%s", temporary_string);
arr_of_strings[l] = malloc((strlen(temporary_string) * sizeof(char)));
strcpy(arr_of_strings[l], temporary_string);
strcpy(temporary_string,"");
}
printRuleOfComparisonInputMessage();
scanf("%d", &rule);
return (0);
}
you cannot change this value: char* temporary_string="";, it's constant and it's same as const char* temporary_string="";, this causes the segmentation fault.
use instead an array of characters.
You must not modify string literals.
Instead of
char* temporary_string="";
You should allocate an modifyable array like this:
char temporary_string[102400];
It is also a good practice to limit the maximum size to read to avoid buffer overrun.
scanf("%s", temporary_string);
should be
scanf("%102399s", temporary_string);
if you use the above array. The maximum length is the length of array minus one because the laste element is for terminating null-character.
Also you must allocate also for terminating null-character.
This means that this line
arr_of_strings[l] = malloc((strlen(temporary_string) * sizeof(char)));
should be
arr_of_strings[l] = malloc(((strlen(temporary_string)+1) * sizeof(char)));
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 6 years ago.
This is what I'm trying to do but my code is either not compiling or giving me an unexpected output "BC" instead of just "B".
#include <stdio.h>
void removeFirstAndLastChar(char** string) {
*string += 1; // Removes the first character
int i = 0;
for (; *string[i] != '\0'; i++);
*string[i - 1] = '\0';
}
int main(void) {
char* title = "ABC";
removeFirstAndLastChar(&title);
printf("%s", title);
// Expected output: B
return 0;
}
I looked through a lot of answers here related to passing pointers by reference but none of them seemed to contain the operations that I want to do in my removeFirstAndLastChar() function.
I do not judge your algorithm or C conventions, friends who comment on your problem are totally right. But if you still do it in this way you can use this approach.
#include <stdio.h>
#include <string.h>
void removeFirstAndLastChar(char* string) {
memmove(string,string+1,strlen(string));
string[strlen(string)-1]=0;
}
int main(void) {
char title[] = "ABC";
removeFirstAndLastChar(title);
printf("%s", title);
// Expected output: B
return 0;
}
This question already has answers here:
Modifying String Literal [duplicate]
(4 answers)
Closed 10 years ago.
I am trying to remove two consecutive duplicate elements from the string.I am getting segmentation fault in the line 16 .even the commented 17th line also get me the same error.
dont worry about my logic of my program.it may be wrong...but i am struck with this error..help me out...explain why i am getting this error
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *st="fvvbbyyr";
int i=0,j,len;
for(len=0;st[len]!='\0';len++);
for(i=0;i<len;i++)
{
if(st[i]==st[i+1])
{
for(j=i+2;j<len;j++)
{
*(st+j-2)=*(st+j);
//st[j-2]=st[j];
}
len = len-2;
i=-1;
}
}
return 0;
}
char *st = "fvvbbyyr";
st points to the anonymous string "fvvbbyyr", which can be located in read-only memory.
*(st+j-2) = *(st+j);
Attempting to modify such value leads to an undefined behavior.
A good habit is to declare the pointer as const char * because a string litteral behaves in this way.
const char *st = "fvvbbyyr";
Then your compiler should print some warnings/errors. Use rather an array:
char st[] = "fvvbbyyr";
BTW, the array subscripting operator [] may make your code more readable.
st[j - 2] = st[j];
Moreover you are accessing to st[i+1] == st[len] once in your loop.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why do I get a segmentation fault when writing to a string?
Why do I get a segmentation fault when I try to modify a string constant?
I was trying to run the following two codes and I am getting a segmentation fault with file2.c but with file1.c I am not getting any fault. Can somebody explain what is the difference between the following codes :
file1.c
#include <stdio.h>
int main()
{
int i;
char string[11] = {"HelloThere"};
string[10] = '\0';
for(i =0;i<5;i++)
{
string[i] = 'a';
}
printf("%s\n",string);
}
and :
file2.c
#include <stdio.h>
int main()
{
int i;
char * string;
string = "HelloThere";
for(i =0;i<5;i++)
{
string[i] = 'a';
}
printf("%s",string);
}
This is because the assignment
char string[11] = {"HelloThere"};
copies the string constant into a writable memory, while
char * string = "HelloThere";
leaves it in the read-only memory. While it is absolutely OK to write to the writable memory (duh!) writing to read-only memory is undefined behavior, and may trigger a crash.
Note that you do not need to specify the size of your string explicitly, unless you want to allocate more memory than is required for your string literal:
char string[] = {"HelloThere"}; // <<== The size is empty
string = "HelloThere";
then
string[i] = 'a';
is wrong - you're trying to modify a string literal, which you can't. This results in undefined behavior, so anything can happen, including crashes.
However,
char sring[11] = "HelloThere";
creates an auto array (copying the contents of the string in it beforehands) and that's writable, it's allowed to modify their elements.