Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

String concat using pointers

Status
Not open for further replies.

dhanraj_kmr

Advanced Member level 4
Joined
Sep 23, 2008
Messages
117
Helped
3
Reputation
6
Reaction score
3
Trophy points
1,298
Location
Chennai, INDIA
Activity points
2,174
Dear All,
I am trying to concat two strings and store it in third pointer. but After i assign 50 bytes memory to str1, i am not able to write any value to that location.

Code:
int main(void) {
     char *str1;
     char *str2 = "Tom";
     char *str3,i = 0;

    str1 = malloc(50 * sizeof(char *));

     if (str1 != NULL){
        *str1 = "My name is"; //This line is not effective. why?

         str3 = str1;
        while(*str1++ != '\0');
        -- str1;

        while(*str2 != '\0')
            *str1++ = *str2++;
        *str1 = '\0';
        printf("%s\n",str3);
     }
     return 0;
}

Can any one explain why my method is wrong?
 

Hi dhanraj_kmr,

the code you are writing is very wrong. First of all you should use standard libraries if available: in this case all the things you are doing are already implemented and, above all tested, in the string library of C. Just use the functions "strcpy" and "strcat" for your purposes. They are defined in the "string.h" standard header.

In addition, there are at least the following errors:

1. you allocate heap with malloc but you never free it: add a free instruction at the end of main;

2. while allocating with malloc you are specifying an incorrect amount of data: you are trying to allocate space for 50 chars, that would require 50 bytes, but with the code provided you are allocating 50*4 bytes;

3. the following initialization is not reliable (actually, I guess this is compiler-dependent)
Code:
*str1 = "My name is";
To do this use the string functions:
Code:
strcpy(str1, "My name is");
that is much more reliable;

4. the while loops in which you are trying to copy additional chars can be deleted, and the following simple code works just fine:
Code:
str1 = strcat(str1, str2);

Cheers
 
  • Like
Reactions: FvM

    FvM

    Points: 2
    Helpful Answer Positive Rating
*str1 = "My name is"; //This line is not effective. why?
Counterquestion: Do you have any indications that the expression is using recognized C syntax? I agree with kingslayer that some compiler may support it as an extension, but you'll hardly find it in a C text book.

In addition, the below loop is positioning the pointer behind the terminating null character, thus it doesn't work for the concatenation.
Code:
while(*str1++ != '\0');

Beside this two points, the code should work, if you want to avoid standard string functions for any reason.

According to K&R (Chapter 5.5, 2nd edition), both below constructs are valid initializers, of course with different properties
Code:
char amessage[] = "now is the time"; /* an array */
char *pmessage = "now is the time"; /* a pointer */

2. while allocating with malloc you are specifying an incorrect amount of data: you are trying to allocate space for 50 chars, that would require 50 bytes, but with the code provided you are allocating 50*4 bytes;

I think it allocates memory space for 50 characters.
 
Last edited:

I think it allocates memory space for 50 characters.

Actually the following code

Code:
 str1 = malloc(50 * sizeof(char *));

is allocating space for 50 entries of size given by

Code:
sizeof(char *)

but a pointer to any type is 4 bytes in a 32-bits architecture. To have space for 50 chars he should have written (with an additional cast conversion for warning removal):

Code:
 str1 = (char *) malloc(50 * sizeof(char));

Cheers
 
  • Like
Reactions: alexan_e and FvM

    FvM

    Points: 2
    Helpful Answer Positive Rating

    alexan_e

    Points: 2
    Helpful Answer Positive Rating
You are right of course. I simply didn't notice the pointer operator, probably because it doesn't seem to make any sense in this place.
 

Thanks for all the replies.
I think
Code:
        *str1 = "My name is"; //This line is not effective. why?
will not work since the string is stored in an address. But i am assiging to a pointer value.

I have modifed to below new code and facing a segment fault.

Code:
int main()
{
    char *str1 = "My name is ";
    char *str2 = "Dhanaraj";
    char *str3;

    str3 = malloc(20);

   if (str3 != NULL){  

    str3 = str1;
    while(*str3++ != '\0');
    --str3;
    while(*str2 != '\0'){
        printf("\n%c", *str2);
        *str3 = *str2; // Segment fault when control comes here. Why?
        str3 ++;
        str2 ++;
    }

    *str3 = '\0';

    str3 = str1;

    printf("%s", str3);
    free(str3);
}
    return 0;
}

Can you explain why segment fault here? But if i do by passing to another function and modify, there is not issue. Below code no issues.

Code:
void strcatt(char *str1, char *str2, char *str3)
{
    while(*str1 != '\0')
    {
        *str3 = *str1;
        str3 ++;
        str1 ++;
    }

    while(*str2 != '\0')
    {
        *str3 = *str2;
        str3 ++;
        str2 ++;
    }
    *str3 = '\0';
}

int main()
{
    char *str1 = "My name is ";
    char *str2 = "Dhanaraj";
    char *str3;

    str3 = malloc(20);

   strcatt(str1,str2,str3);

/*    str3 = str1;
    while(*str3++ != '\0');

    while(*str2 != '\0'){
        printf("\n%c", *str2);
        *str3 = *str2;
        str3 ++;
        str2 ++;
    }

    *str3 = '\0';*/

    printf("%s", str3);
    return 0;
}
 

Hi,

there is at least one error, and I have at least one doubt.

First, the first occurrence of the following code (the first instruction of the taken if branch)
Code:
str3 = str1;
is not copying the data from str1 to str3, but you are aliasing the data: this means that from that line on, str3 and str1 will point to the same region in which "My name is " is stored. This is totally different from copying the data from one string to the other. Indeed, once you get to the '\0' character through str3, you arrived at the end of the memory for which "My name is " has been allocated. This means that once you do any "str3++" increment, you will have segmentation fault because you are out of the boundary of the string, and you are not pointing to the memory allocated by your malloc.

Secondly, the doubt is the following: I am sorry, but I am again not sure that the initializers will work (is it really ANSI-C??):

Code:
char *str1 = "My name is ";
char *str2 = "Dhanaraj";

I bet that if you use malloc or if you allocate statically both str1 and str2 strings as follows, your code will work unchanged

Code:
char str1[] = "My name is ";
char str2[] = "Dhanaraj";

Cheers
 

I bet that if you use malloc or if you allocate statically both str1 and str2 strings as follows, your code will work unchanged
It won't for sure, you have already stated the reason.

str3 is pointing to the str1 string storage, and the succeeding character copy *str3 = *str2 writes out of bounds, beyond the memory space "My name is ". The malloc() assigned storage is unused (and lost after overwriting str3).

And yes, it is ANSI C.
 

Well, you're true. Unchanged, I mean without that statement :p

Great to know that it is ANSI C. But then, why the with the following it is still segmenting
Code:
char *str1 = "My name is "
while with the following it does not segment?
Code:
char str1[] = "My name is "

I am using gcc version 4.4.3.

Cheers
 

It's not clear for me, to which "correct" code you are referring. It would need to use strcpy(str3,str1) or an equivalent construct to avoid writing out of bounds.

Getting an actual segment fault is a matter of object order and can't be clearly predicted.
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top