C String Concatenation using Function [duplicate] - c

This question already has answers here:
Returning an array using C
(8 answers)
Closed 3 years ago.
I just want to concatenate two strings and a separator using a function.
But in main() I am not getting the concatenated string.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* PathCreation(char* Str1, char* Str2, char* Separator=(char*)"/"){
char CreatedPath[strlen(Str1)+strlen(Str2)+strlen(Separator)+1];
strncpy(&CreatedPath[0], Str1, strlen(Str1));
strncpy(&CreatedPath[strlen(Str1)], Separator, strlen(Separator));
strncpy(&CreatedPath[strlen(Str1)+1], Str2, strlen(Str2));
CreatedPath[strlen(Str1)+strlen(Str2)+1]='\0';
//printf("\n%s", CreatedPath);
return CreatedPath;
}
int main(void)
{
char str1[] = "foo";
char str2[] = "bar";
char* ccat=PathCreation(str1, str2);
puts(str1);
puts(str2);
puts(ccat);
}

Since you've been programming in C style, I'll stick to C style. But I should point out that your code is only valid in C++ because of the default argument.
The issue is that when you simply declare something you're allocating it to the stack, stacks are destroyed once a function exits and attempting to use data after the stack has been destroyed is undefined behaviour, which means that the code may work as you expect on occasion but it may also end up pointing to garbage or simply crashing.
Instead you'll need to allocate it on the heap so that it persists after the function exits. Replace the line where you allocate your string with:
char* CreatedPath = (char*)malloc(sizeof(char)*(strlen(Str1)+strlen(Str2)+strlen(Separator)+1));

Related

Cannot use strcpy with 2 string (segmentation fault) [duplicate]

This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed last year.
What's wrong with this code?:
int main(int argc, char ** argv) {
char strs[] = "What will be printed?";
char *str1;
char *str2;
strs[5] = '\0';
str1 = strs;
strcpy(str2, str1);
printf("%s\n", str2);
return 1;
}
I want it to print "What", instead i get segmentation fault.
I believe it has something to do with the strcpy(str2, str1);, but what is the explanation for that? The signature of strcpy is char* strcpy(char* destination, const char* source); and that's exactly what i did.
Could you explain that to me?
Your destination string is not initialized - it has no memory reserved for itself. An attempt to write to it causes invalid memory access (you're trying to overwrite something completely random and unplanned) and is followed by a segmentation fault.
One clean way to initialize a string is to define a global macro variable that just sets the largest size of strings you plan on using in your code,
#define MAXBUF 100
Then in your main you can simply write:
char str2[MAXBUF];
And your program will work. Alternative is to use dynamic memory allocation which you will likely learn about soon.
#include <stdio.h>
#include <string.h>
int main() {
char *src = "What will be printed?";
char dest[100];
int START = 0; // start of copy
int LENGTH = 5; // length of copy
// copies up to LENGTH characters from the string pointed to, by src to dest. In a case where the length of src is less than that of LENGTH, the remainder of dest will be padded with null bytes.
strncpy(dest, &src[START], LENGTH);
printf("%s\n", dest);
return 0;
}

Write string into initialised blank char array [duplicate]

This question already has answers here:
Assigning char array a value in C
(2 answers)
Closed 8 years ago.
i have just started learning C and i am confused on how to write a string into a simple char array in C. i understand that C does not have a string data type, and i read that most websites declare string in one of this way
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char greeting[] = "Hello";
however what if i have initialized a char array of
char greeting[50];
and i try to give it a string value.
char greeting[50];
greeting = "Zack";
i am given a error, why?
strcpy is designed to copy "strings".
Use as follows:
char greeting[50];
strcpy(greeting, "Zack");
Be aware of potential overruns if the destination isn't big enough.
Use standard function strcpy declared in header <string.h> that to copy a string in a character array
#include <string.h>
//...
char greeting[50];
strcpy( greeting, "Zack" );
There are other functions declared in header <string.h> that also can be used to copy strings in character arrays. For example
memcpy
strncpy
strcat
strncat
An example of using strcat instead of strcpy
#include <string.h>
//...
char greeting[50];
greeting[0] = '\0';
strcat( greeting, "Zack" );
Arrays have no the assignment operator. So the compiler issues an error for this code snippet
char greeting[50];
greeting = "Zack";
But there is a trick when you may assign character arrays. To do that you need to enclose a character array in a structure and use a compound literal. For example. Contrary to arrays structures have the assignment operator that performs member-wise copy of structure.
#include <stdio.h>
#include <string.h>
int main(void)
{
struct A { char greeting[50]; } s;
s = ( struct A) { "Zack" };
puts( s.greeting );
return 0;
}
The output will be
Zack
That this code would be compiled you need a compiler that supports C99.
You use strcpy():
char greeting[50];
strcpy(greeting, "Zack");
This will copy the four characters and the terminating zero into greeting.
Beware that it knows nothing about the available space at greeting, so it's perfectly possible to do the wrong thing.
You're getting an error because you're basically trying to assign a string constant to an array. The array greeting decays to a pointer, but it's a char *const pointer.
You need to use strcpy to copy the literal.
In C, the folowing code will print "foo":
char greeting[50];
if(greeting == &greeting[0]){
printf("foo");
}
else{
printf("bar");
}
This happens because the variable of the array (greeting) contains a pointer to the first element of it (greeting[0]).
So, if you asign:
greeting = "Zack";
You are saying: Let greeting have the address of where the literal string "Zack" is in the memory.
As changing the address of a array is not allowed, you get an error.

recursive strcpy function [duplicate]

This question already has answers here:
Access violation when using strcpy?
(8 answers)
Closed 9 years ago.
#include <stdio.h>
char *strcpy_r(char* s, char* t);
int main()
{
char *s = {"Bob"};
char *t = {"Billy"};
char *ptr;
ptr = strcpy_r(s, t);
printf("%s\n", ptr);
return 0;
}
char* strcpy_r(char* s, char* t)
{
if((*s = *t) != '\0')
strcpy_r(s + 1, t + 1);
return s;
}
I'm just doing this for practice, but when I compiled it. I got a seg fault from main. Could someone tell me what might've caused this seg fault?
Congratulations, you have invoked undefined behavior twice within one line.
First, you can't modify the contents of a string literal. So strcpy()ing onto "foo" is wrong.
Two, even if you could: you're copying a string to a buffer that is shorter than the string. This is UB again.
You are trying to modify a constant string. This is wrong! Chances of segfault live when you modify a constant string.
Instead do this:
char s[10] = "Bob";
char t[10] = "Billy";
char *ptr;
You can't overwrite the memory that's used to hold a quoted string. That'll segfault instantly.
String literals are constant, i.e. they cant change. You're also trying to copy a longer string into a shorter string, which will write beyond the bounds of the destination string.
Both of these problems leads to undefined behavior which can cause a crash.
To solve the first problem, you have to use an array for the destination string. To solve the other problem, you have to make sure the destination array is at least as large as the source string (including its terminating '\0').

Increment character value of a string [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why do I get a segmentation fault when writing to a string?
Here is a small function, was testing something so wrote it. Here i tried to increment a character value of the string literal when i tried doing so i got a segmentation fault. Can you please tell what i am doing wrong here
#include <stdio.h>
int input_string(char *str)
{
printf("%s\n", str);
printf("%c\n", *str);
printf("%c\n", (*str)++); // I get a segmentation fault here, cant i increment the value like this ?
}
void main()
{
char *str = "andrew";
input_string(str);
}
What this char *str = "andrew"; does is create a pointer to a string that MAY be located on .text (where the executable code resides) and trying to modify it is undefined behavior.
Change it for this:
char str[] = "andrew";
It will make a copy of the string in a stack allocated buffer that you can safely modify.
This:
char *str = "andrew";
means what str points to a constant string literal. You will get undefined behavior if you try to change it.
If you want to perform string manipulation, define a character array.

How to reverse string correctly? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to reverse a string in place in c using pointers?
I was trying to reverse a string using C.
A segmentation fault occurs. Any idea why?
Here's my code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *str1 = "abbd";
char *str2;
str2 = str2 + strlen(str1)-1;
while(*str1 != '\0')
*(str2--) = *(str1++);
printf("%s", str2);
return 0;
}
Nothing's properly allocated (allocate the proper length at declaration or malloc it) and you don't really move through the strings and check for the end of your condition as fitted (try str[i]). You have awaken the kraken.
Looks like you didn't allocate any space for str2, just made the pointer.
char *str2;
str2 = str2 + strlen(str1)-1;
You declared a pointer str2, but initialize its value to garbage. (str2 + ...)
Are you trying to do an in-place modification? That won't work for this code, the char *foo="bar"; format places the "bar" in a write-protected memory space on platforms that support it.
Are you trying to do an out-of-place modification? If so, you forgot to allocate that space.
You're not allocating memory for str2.
str2 = (char *)malloc(sizeof(char) * (strlen(str1) + 1));
I haven't tried it, but it seems like you're going to want to set str2 = str2 + strlen(str1), otherwise I think you'll run off the "front" of your str2 buffer as well.
I would recommend treating your strings as arrays, and let the compiler do the pointer arithmetic for you.

Resources