Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have this two arrays, codeblocks doesn't give me any build error but whenever I run it, it gives "Segmention fault" and it shuts the program down I've debugged it and found out I can't change values from names1 this way but changing names2 this way works just fine, is there a way to make this work? If yes how do I make troca work for names1?
void troca(char* frase){
unsigned i=0;
while(*(frase+i)!='\0') {
if(*(frase+i)=='O') {
*(frase+i)='0';
}
i++;
}
}
int main(){
char *names1[]={"JOAO","MANUEL","ROBERTO","ZE"};
char names2[][51]={"JOAO","MANUEL","ROBERTO","ZE"};
unsigned i;
for(i=0;i<4;i++) {
troca(names2[i]);
}
return 0;
}
The difference is:
names1 is declared simply as an array of string pointers without other defined characteristics. Using string literals here will put the string literals into a section in your executable file which is read-only, because the compiler can this way re-use them. For example, when you use char* a = "abc"; char* b = "abc"; then most likely a and b will have equal memory addresses as values. This means you can't modify them, so you get a "Segmentation fault" (another name for the same error is "Access Violation").
names2 is declared as an array of arrays of chars. Assigning a string literal there will copy the data of the strings into the array, and since there is no const thing in play in your code, the array has to be mutable, so in turn your strings stored in the char arrays are mutable as well.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to write a program that converts a string to morse code. It currently works fine whenever input is a string literal but whenever I send a string as a variable I get a segmentation fault.
void morseCode(char* s)
{
for (int i = 0; s[i]!='\0'; i++)
printf("%s",morseEncode(s[i])); //morseEncode is a function which returns char* of morse code
}
int main()
{
int length = strlen("Hello");
char* s = (char*) malloc(length + 1);
s = "Hello";
morseCode(s); // Segmentation fault
morseCode("Hello"); // works fine
return 0;
}
This is a result of passing the variable s to morseEncode (which presumably modifies it) as modifying s is undefined behaviour. Specifically, modifying a string literal in such a manner is undefined behaviour per 6.4.5p6 [from C99:TC3]
It is unspecified whether these (string literal) arrays are distinct provided their
elements have the appropriate values. If the program attempts to
modify such an array, the behavior is undefined.
(text in parentheses added by me)
You might also want to take a look at this question.
You could instead declare s like so (with automatic storage duration).
char s[] = "Hello";
If you need s to be a pointer you could try
// Yes, sizeof(char) will always be 1 and you could remove it.
char *s = malloc(sizeof(char) * (strlen("Hello") + 1));
strcpy(s, "Hello");
// Your code that uses s here
free(s) // Important!
As an additional note #kaylum has pointed out that the original answer didn't provide a justification as to why calling the function in the two different ways produced different results. This is because the undefined behaviour you're running into just so happened to be undefined in a different way for each call. If I write out a similar program and compile it using gcc (with no flags) I end up running into a segfault both ways; on the other hand, compiling with clang -O both work! Its simply a product of whatever segment(s) of memory your specific compiler has decided you place each of those sequences of characters.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'v encountered "Segmentation fault (core dumped)" when compile my C program in *nix. I've narrowed the mistake to this line (without this line my program can run):
strcpy(con[count], "1234");
Before that, I declared con as:
char *con[30];
And count is always smaller than 30.
What's wrong with this line? How should I change it?
char *con[30];
declares an array of 30 pointers to strings. This is not what you need. It fails because you then try to copy to the first string, but did not allocate the first string (only a pointer to it)
You need
char con[30];
and then
strcpy(con, "1234");
Or (as Lee Danial points out) you might have wanted an array , in which case you need
char *con[30];
then
con[count] = strdup("1234")
or
con[count] = "1234"
The first one allocates a string and copies it for you (a combination of malloc and strcpy). The second one just points at the supplied literal, it doesn't make a copy. Hard to say which is 'best' for you.
PS strdup is equivalent to
x = malloc(strlen(str) + 1);
strcpy(x, str);
return x;
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
i'm getting segmentation fault core dumped when im using strtok at the next code part. the code is getting debugged but when I run it I get the segmentation fault. How can I fix it?
struct{ char *name;
void(*func)(void);
}cmd[]={
{"read_cm",read_cm},
{"NA",NULL}
};
int d;
char *s="_\n";
char *token2;
for(d=0;cmd[d].func!=NULL;d++)
{
token2=strtok((cmd[d].name),s);
}
You may not modify a string literal. Any attempt to modify a string literal results in undefined behavior.
The standard C function strtok tries to insert a terminating zero while splitting a string into substrings.
To resolve the problem use a character array instead of the pointer name. Or allocate memory dynamically and copy a string to the allocated memory pointed to by the pointer name.
For example
struct
{
char name[8];
void(*func)(void);
} cmd[] =
{
{ "read_cm", read_cm },
{ "NA", NULL }
};
Another approach is to use standard C functions strcspn and strspn instead of strtok to find substrings.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
my program
#include<stdio.h>
#include<conio.h>
char* mystrcat(char* , char* );\\ function declared as global
main()
{
char dest[50]="hello"; \\destination string
char src[50]="readers"; \\source string
clrscr();
mystrcat(dest,src);\\function calling but does not have receiving array
puts("after concatenation"); \\ of strings
puts(dest);\\shows "helloreaders"<-- how?
getch();
return 0;
}
char* mystrcat(char* des, char *sr)\\for concatenating two strings
{
int i=0,j=0;
while(des[i]!='\0')
{ i++;}
while(sr[j]!='\0')
{
des[i]=sr[j];
i++;j++;
}
des[i]='\0';
puts(sr);\\"readers"
puts(des);\\"helloreaders"
return sr;\\returning source string
}
output:
readers
helloreaders
after concatenating:
helloreaders
I am returning only source string from mystrcat(). But how compiler knows the modified destination string? Since I declare the function globally the compiler knows the modified string?
It is not because of return sr, rather it is because char* mystrcat(char* des, char *sr) modified its argument ( des ). Even if you change the return value to just an int, the result will be same. The reason is when you pass a char[] variable to a function, you just pass a pointer, anything you did inside the function to the variable will be reflected to the caller.
When you called function
mystrcat(dest,src);\\function calling but does not have receiving array
you passed as arguments two arrays that are implicitly converted to pointers to first elements of each array.
So inside the function you deal with addresses of the memory extents occupied by the arrays. And you write in the memory occupied by the destination array elements of the source array
while(sr[j]!='\0')
{
des[i]=sr[j];
i++;j++;
}
des[i]='\0';
because des and sr hold addresses of first elements of the arrays.
So the memory occupied by array dest was overwritten.
You are giving mystrcat() a pointer to dest and when it writes through that pointer, it changes dest directly. It doesn't matter what the function returns. des[] in mystrcat() is not a copy of dest[] in the main program, it's the same thing.
because parameters you pass to the function are points,arrays they point to are changed, but these points are not changed
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
In my code FILES is struct.
typedef struct {
char name[64];
char filename[64];
long size; // file size
long loaded; // after load of kernel loaded should be same value as size
char * program;
} FILES;
files is array of type FILES.
FILES files[MAX_KERNELS_COUNT];
in function loadKernels I would like to access member of the array files via pointer.
bool loadKernels(const char * path, FILES * files, int count)
{
...
size = strlen(files[c].program);
printf("\n%ld\n",size);
size = sizeof(files[c].program);
printf("\n%ld\n",size);
...
}
I have problem there on the line with files[c].program . I know that I must access files like a pointer but how to do it correctly to obtain the length of the C string? I know something like (*files)[c].program is wrong.
files is an array of FILES.
files[c] is thus of type FILES
files[c].program is thus of type char *.
so strlen(files[c].program) should give you what you want, i.e. the length of the string (as opposed to the size of the pointer). Note strlen will exclude the terminating NUL, i.e. the size of the string will be one byte longer.
size = strlen(files[c].program);
printf("\n%ld\n",size);
size = sizeof(files[c].program); //<-- Here you are using the sizeof. change this into strlen
printf("\n%ld\n",size);
Sizeof gives you sizeof the given variable. It will not give you the string length.
I have problem there on the line with files[c].program . I know that I
must access files like a pointer but how to do it correctly to obtain
the length of the C string? I know something like (*files)[c].program
is wrong.
There is no string
program is a pointer to somewhere outside the array.