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)));
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)
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;
}
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 5 years ago.
#include<stdio.h>
#define ASIZE 50
void Reverse(char *str){
int Asize,i=0;
char temp;
// Find the length of the string
while(*(str+i)!='\0'){
i++;
}
Asize=i;
// string reverse
for(i=0;i<(Asize/2);i++){
temp = *(str+i);
//may be below is some error with first input method 1
//but for input method 2 it works perfectly
*(str+i) = *(str+(Asize-(i+1)));
*(str+(Asize-(i+1))) = temp;
}
}
int main()
{
//input method 1. (error aries while i pass the pointer as argument)
char *s = "abcxyz";
//input method 2 (works perfectly while as function parameter)
char s[ASIZE];
scanf("%s",s);
Reverse(s);
printf("%s",s);
}
In the main the input method 1 not working perfectly for the reverse of the string, but the method 2 works.
The concept of mine is not clear with the memory representation of char pointer. Maybe I am not good to make the question correctly but Would someone please make me clear why the method 1 is not working. Thanks in advance for the help.
"abcxyz" is actually a const char[7] type that can decay to a const char* in certain situations.
It is not a char* type; the behaviour on attempting to modify the string is undefined.
char s[ASIZE]; on the other hand is an array of char with automatic storage duration. You are free to modify any element of that as you please.
This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed 6 years ago.
I understand that: I can use a two-dimensional array for storaging many strings. But, I would like to solve this problem with one-dimensional; so, please do not advise me to use two-dimensional array for solving.
I have a small one-dimensional array, which is used for storaging many strings. Here is all of source code:
#include <stdio.h>
void main()
{
#define MAX 10
int N = 3;
char * str[MAX];
printf("Input a string in each line:\n\n");
for (int i = 0; i < N; i++)
{
printf("str[%d] = ", i);
gets(str[i]);
}
printf("\n\n---\n\nExport the list of strings:\n\n");
for (int j = 0; j < N; j++)
{
printf("str[%d] = ", j);
printf("%s\n", str[j]);
}
}
When I compile it, the compiler does not return any error or warning. But, after I inputted the data, there is an error message from Windows:
A problem caused the program to stop working correctly
Then, my program is broken.
In this array: char * str[MAX]
None of the entries is initialized to point to a valid (properly allocated) memory block.
And so you should not scanf("%s", &str[i]) until you have initialized entry #i.
char * str[MAX];
str is an array of pointers. You should allocate memory to pointers before writing anything to it.
str[i] = malloc(20);/* Showing an example of using malloc() . How much memory should be allocated is left to you */
Using a scanf() to scan a string is not a good idea I would rather prefer fgets()
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.
I was trying out a sample program to understand about the generic swap function.
/* A simple generic swap function */
#include<stdio.h>
#include<string.h>
void swap(void* xp,void* yp,int size){
//void temp = *xp; // we cant declare a variable as void , as we need to konw to de-reference as its not specifying any size info
// Hence used the smallest type info - char
char buffer[size];
memcpy(buffer,xp,size);
memcpy(xp,yp,size);
memcpy(yp,buffer,size);
}
int main(){
int a = 10;
int b = 20;
double d=1.34;
double e=2.34;
char* s = "Hello";
char* t = "World";
printf("\n a : %s b : %s \n",s,t);
swap(s,t,sizeof(char*));
printf("\n a : %s b : %s \n",s,t);
return 0;
}
I got a segmentation fault when I ran the above program with the function call as swap(s,t,sizeof(char*)). But if I run it with swap(&s,&t,sizeof(char*)), I don't get any segmentation fault.
gdb o/p:
Breakpoint 2, swap (xp=0x4007ac, yp=0x4007b2, size=8) at swap_generic1.c:5
5 void swap(void* xp,void* yp,int size){
(gdb) s
8 char buffer[size];
(gdb) s
9 memcpy(buffer,xp,size);
(gdb) s
10 memcpy(xp,yp,size);
(gdb) s
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b64fe4 in ?? () from /lib/x86_64-linux-gnu/libc.so.6
what might be the cause of the problem. Is that when passed as s and t, the argument is assigned with the address of the strings "Hello" and "World" respectively, and the pointer increments goes sto some other location to fetch the values.
You are calling the swap functions with sizeof (char *), so you expect to only swap pointers. But you fail to pass pointers to the pointers, instead passing the values of the pointers themselves.
This will make swap() try to swap sizeof (char *) characters in the strings, which is not allowed since character literals generate constant data which cannot be written.
You should call it as:
swap(&s, &t, sizeof s);
to just swap the pointer values, not move any character data around.
char* s = "Hello";
char* t = "World";
Both are pointer pointing to string literal (constant string). The compiler puts that in a part of memory that is marked as read-only. If you try to change that it will result in a memory access violation.
The pointers you pass to your swap function are string literals and writing to an element in a string literal is undefined behaviour. That is why you get the segfault