Kavi Kavi Kavi Kavi - 3 months ago 21
C Question

Copy String from one pointer to another in same process and between 2 processes

So I was asked these 2 questions in my interview-

1-what if I have a code snippet like this in C what will be the output

char *ptr1=malloc(10);
ptr1="abc";
char *ptr2 = malloc(20);
ptr2="defghi";
strcpy(ptr1,ptr2);
printf("%s",ptr1);


I tried this one on my terminal after getting home and it was giving this error

[1] 7673 bus error ./b.out


I would like to know how to copy the string in such a case from one pointer to another.

2- We have 2 processes A and B

This is the code in process A

char *ptr1=malloc(10);
ptr1="abc";
char *ptr2 = malloc(20);
ptr2="defghi";
strcpy(ptr1,ptr2);


now the address of ptr1 is passed to process B using interprocess communication and the code in process B is as follows (ptr1 is the address from process A)

char *ptr3=malloc(10);
ptr3=ptr1
printf("%s",ptr3);


What would be the output of this? If the ans is garbage value or error then in what way can we make ptr3 point to the string pointed by ptr1.

Answer

I would like to know how to copy the string in such a case from one pointer to another.

You can't. Pointers do not contain strings, or their characters. They can, however, point to null-terminated arrays of characters, i.e. strings.

Having that in mind, it is important to understand that here:

char *ptr1=malloc(10);
ptr1="abc";

you allocate block of memory (or try to do), assign its address to variable ptr1, and then immediately overwrite that pointer value with a pointer to the arrary represented by string literal "abc". The original pointer value is lost -- you leak that memory. In particular, the assignment absolutely does not copy the characters of the literal into the allocated space.

Now be aware that attempting to modify any part of a string literal invokes undefined behavior, whether the modification is direct or indirect. This:

strcpy(ptr1,ptr2);

constitutes an attempt to modify string literal "abc" indirectly via pointer ptr1. If the question was "what is the output" then it was a trick question. The program has undefined behavior -- it's output cannot be predicted, at least not from the C code alone.


The IPC case is a different trick question. Pointer values are meaningful only in the context of the process in which the pointer was obtained. If you pass that pointer to a different process via some form of IPC, there is no reason to suppose that it is valid in the receiving process. Even if it happens to be valid, there's no telling what it points to. If you want to send a string to another process then you must send the characters, not the pointer.

Comments