Segmentation fault (core dumped) with strcpy [closed] - c

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;

Related

Segmation fault when sending a string as a paremeter [closed]

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.

why am i getting segmentation fault core dumped? [closed]

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.

Array of Struct pointers, get segfault in c [closed]

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
#define MAX_SPACES 10
#define MAX_SIMPLE_EVENTS 5000
#define MAX_USER_EVENTS 1000
struct {
EventSpace* p_spaces[MAX_SPACES];
SimpleEvent* p_simple_events[MAX_SIMPLE_EVENTS];
UserEvent* p_user_events[MAX_USER_EVENTS];
}* G_manager;
static void add_space(EventSpace* space){
static uint16_t index = 0;
(*G_manager).p_spaces[index] = space;
}
After running in gdb got:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400559 in add_space (space=0x7fffffffdf30)
How to impove it?
At least in the code you're showing, you haven't actually allocated the memory for the structure containing the arrays; you've only created a pointer. So when you dereference that pointer meaning to write into an instance of the structure, you hit a random memory address and got the relatively tame result of your program crashing.
You could change G_manager from a pointer-to-struct to an instance of the struct itself; or you can malloc a buffer big enough for the structure and assign that buffer to G_manager

C Sprintf Format Error [closed]

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'm trying to format the given string and printf it. Bu it doesnt work. It gives error Any idea?
char* query_buffer;
sprintf(query_buffer,"%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x;%u.%u.%u.%u;%d\n",
node_config->mac_address.addr[0], node_config->mac_address.addr[1], node_config->mac_address.addr[2], node_config->mac_address.addr[3],
node_config->mac_address.addr[4], node_config->mac_address.addr[5], node_config->mac_address.addr[6], node_config->mac_address.addr[7],
ip64_addr->u8[0], ip64_addr->u8[1], ip64_addr->u8[2], ip64_addr->u8[3],
node_config->coap_port);
printf("%s\n",query_buffer);
If I try below printf it works. I couldnt understand what is different between doing these two.
printf("%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x;%u.%u.%u.%u;%d\n",
node_config->mac_address.addr[0], node_config->mac_address.addr[1], node_config->mac_address.addr[2], node_config->mac_address.addr[3],
node_config->mac_address.addr[4], node_config->mac_address.addr[5], node_config->mac_address.addr[6], node_config->mac_address.addr[7],
ip64_addr->u8[0], ip64_addr->u8[1], ip64_addr->u8[2], ip64_addr->u8[3],
node_config->coap_port);
The line char* query_buffer; declares a pointer to a char but it the memory it points to might not be declared. So you can get a segmentation fault when you call sprintf to access that memory. Try declaring query_buffer like char *query_buffer = (char*)malloc(256);. That will create a pointer and declare 256 bytes at where it points to.

changing strings in array of char pointers [closed]

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.

Resources