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 2 years ago.
Improve this question
Why the below code results in segmentation fault?
#include<studio.h>
#include<string.h>
int main ()
{
char *name="Kaveri";
char *rd="Rajshekhar";
strcat(name,rd);
puts(name);
return 0;
}
For strcat() to work, the destination buffer must be writable and long enough to hold the concatenated output with null termination. From the man page:
The strcat() function appends the src string to the dest string, overwriting the terminating null byte ('\0') at the end of dest, and then adds a terminating null byte. The strings may not overlap, and the dest string must have enough space for the result. If dest is not large enough, program behavior is unpredictable;
In your case, the destination is a pointer to the first element of a string literal, attempt to modify which invokes undefined behaviour.
Segmentation fault is one of the many side effects of undefined behaviour.
To solve this, either
make the name an array, with a big-enough dimension, like
char name[128] = "Kaveri";
use allocator function to allocate enough memory to name, like
char *name = malloc(128); //sizeof(char) == 1
strcpy(name, "Kaveri");
and then use name as the destination buffer for strcat.
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 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 6 years ago.
Improve this question
int main()
{
char* in = (char *)malloc(sizeof(char)*100);
in = "Sort of Input String with LITERALS AND NUMBERS\0";
free(in);
return 0;
}
Why this code isn't working with this error?
pointers(10144,0x7fff78a82000) malloc: *** error for object 0x10ba18f88: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
bash: line 1: 10144 Abort trap: 6 '/Users/.../Documents/term2_sr/pointers'
[Finished in 0.1s with exit code 134]
Because in is re-assigned by in = "Sort of ...";.
Actually, you're doing free("Sort of ...");, which is obviously illegal.
in is a pointer. You set it with malloc(), you later change it to point to a literal. Then you try to free this poitner to a litteral (which was never allocated on the heap, so causes free() to fail) .
To copy a string, you have to use strcpy():
char* in = malloc(sizeof(char)*100);
strcpy (in, "Sort of Input String with LITERALS AND NUMBERS");
free(in);
Actually, in order to avoid accidental buffer overflows, you could also copy the string, taking into consideation its maximum length:
strncpy (in, "Sort of Input String with LITERALS AND NUMBERS", 100);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
i need to detect the problem in the next code, and the reason to that problem and how to fix it. for some reason when i tried to run it in visual the error is on the free.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
int main()
{
char str1[] = "abcde";
char* str2 = (char*)malloc(strlen(str1));
strcpy(str2, str1);
puts(str1);
puts(str2);
free(str2);
return 0;
}
strlen return the length of null terminated string excluding the null character '\0'. You need to allocate space for null character too.
char* str2 = malloc(strlen(str1) + 1); // Do not cast return value of malloc
it should be
char* str2 = (char*)malloc(strlen(str1)+1);
The issue, as others have mentioned, is that you're not allocating enough space for the string you want to copy. strlen returns the number of characters in the string, however that number doesn't include the null byte at the end that terminates the string.
So when you call strcpy, you're writing one byte past the end of the allocated memory. Once you write past your memory bounds, that invokes undefined behavior. That means your program might appear to work, it might crash (sometimes right away, sometimes later), or it might cause data corruption that would be hard to detect.
In this particular situation, the extra byte you wrote probably corrupted data used by the implementation of free and/or malloc. But with some other compiler or OS, it might work fine.
So to avoid undefined behavior, be sure to allocate the required amount of space:
char* str2 = malloc(strlen(str1) + 1);
Also, don't cast the return value of malloc, as that may mask other errors in your code.
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
i would like to know if strdup adds a '\0' at the end of the new array if the src array does not contain one ?
let's assume we have an array containing "hello" allocated by this kind of malloc
malloc(sizeof(char) * 5);
so 5 bytes for 5 characters.
I guess the src string did not received the sufficient memory for the '\0'.
What is supposed to happen in this case ?
First the standard disclaimer: strdup isn't a standardized function, so exactly what it does could (at least in theory) vary from one compiler to the next. That said, every implementation I've seen of it has worked the same way.
strdup will determine the length of the input string--it'll start from the address in the pointer you pass, and find the first NUL byte after that location. Then it'll allocate a new block of memory and copy the bytes in that range to the newly allocated block.
So one of two things will happen. Either the input will contain a zero byte, and the result will too, or else strdup will read past the end of the input you passed, and you'll get undefined behavior (but chances are pretty good it'll find a zero byte eventually, and copy a bunch of extra garbage to the duplicate string).
One other minor note: if you use strdup, and then try to port you code to a compiler that doesn't define it, you might consider writing your own:
char *strdup(char const *s) {
size_t len = strlen(s) + 1;
char *ret = malloc(len);
if (ret != NULL)
strcpy(ret, s);
return ret;
}
That's obviously a pretty easy thing to do, but it has one other problem: including it in your code produces undefined behavior. You're not allowed to write a function with a name that starts with str. Those are all reserved for the implementation. So even though the function is simple and the behavior of its content is perfectly well defined, the mere existence of the function as a whole still gives undefined behavior.
What strdup() will do in this case is start with the string passed, and go on looking through memory until it either falls off the end of allocated memory (and you get a SIGSEGV or similar) or finds a byte that happens to contain a '\0'.
It will allocate enough memory to include a copy of everything it scanned, including the '\0', and then copy everything.
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 8 years ago.
Improve this question
I am getting Segmentation fault after return executes. Why is it coming after return and not in strcpy?
int main()
{
char a[2];
strcpy(a,"0123456789101112131415161718192021222324252627282930");
printf("%s\n",a);
return 0;
}
I am getting Segmentation fault after return executes. Why is it coming after return and not in strcpy?
You have made a common mistake called a buffer overflow. This results in undefined behavior, which is a standards answer. However, if you understand how a typical machine uses a stack, you can understand why it crashes when you return. Most CPUs use a down ward growing stack. So before you call strcpy, the stack is something like,
sp + 0 : a[0]
sp + 1 : a[1]
sp + 2 : padding
sp + 3 : padding
sp + 4: return address (four bytes)
The compiler machinery creates a call frame each time you use a function in 'C'. The return address exists as part of stack where the compiler allocates space for your a[] array. As it is under-sized for the string copy, you over-write the return address. This value isn't used until you return. The return address will be overwritten with something like the value 0x34353637 which is the binary pointer for the ASCII text '4567'.
It is advisable to use something like strncpy or an alternative. For example,
strncpy(a,"012345678...", sizeof(a));
a[sizeof(a)-1] = 0; /* ensure the string is terminated. */
Obviously you need to increase the size of your 'a' array if you want the full string to be printed.
Why is it coming after return and not in strcpy?
You get the segmentation fault when main returns because you overwrite critical data (saved frame pointer and return address) in the stack frame of main function and not in the stack frame of strcpy function.
As others already said, you invoke undefined behavior and anything can happen: from nothing to a nuclear war.
You're trying to load a string with a lot more than 2 characters into a char array that only holds 2 characters. This will cause a segmentation fault, since you are overwriting the memory allocated for the char array, which can also cause undefined behavior.
Your program overwrote the buffer, that would cause undefined behavior, which means literally anything could happen.