Aravind mavnoor
Aravind mavnoor

Reputation: 25

string handling in c using pointers

I have written the following program (it is given as an example in one of the best text books). When I compile it in my Ubuntu machine or at http://www.compileonline.com/compile_c_online.php, I get "segmentation fault"

The problem is with while( *p++ = *str2++)

I feel it is a perfectly legal program. Experts, please explain about this error.

PS: I searched the forum, but I found no convincing answer. Some people even answered wrong, stating that *(unary) has higher precedence than ++ (postfix).

#include <stdio.h>
#include <string.h>

int main()
{
char *str1= "Overflow";
char *str2= "Stack";

char *p = str1;
while(*p)
++p;

while( *p++ = *str2++)
;

printf("%s",str1);

return 0;
}

Thanks

Upvotes: 1

Views: 102

Answers (3)

Lundin
Lundin

Reputation: 213862

I feel it is a perfectly legal program.

Unfortunately, it is not. You have multiple, severe bugs.

First of all, you are creating pointers to string literals char *str1= "Overflow"; and then you try to modify that memory. String literals are allocated in read-only memory and attempting to write to them results in undefined behavior (anything can happen).

Then you have while(*p) ++p; which looks for the end of the string, to find out where to append the next one. Even if you rewrite the pointers to string literals into arrays, you don't have enough free memory at that location. You must allocate enough memory to hold both "Overflow" and "Stack", together with the string null termination.

You should change your program to something like this (not tested):

#include <stdio.h>

int main()
{
  char str1[20] = "Overflow"; // allocate an array with enough memory to hold everything
  char str2[]  = "Stack"; // allocate just enough to hold the string "Stack".

  char *p1 = str1;
  char *p2 = str2;
  while(*p1)
    ++p1;

  while(*p1++ = *p2++)
    ;

  printf("%s",str1); // should print "OverflowStack"

  return 0;
}

Or of course, you could just #include <string.h> and then strcat(str1, str2).

Upvotes: 1

user2357112
user2357112

Reputation: 280838

str1 and str2 point to string literals. You aren't allowed to modify those. Even if you could, there isn't enough memory allocated for the string to hold the characters you're trying to append. Instead, initialize a sufficiently large char array from a string literal:

char str1[14] = "Overflow";

Upvotes: 3

Aniket Inge
Aniket Inge

Reputation: 25705

Because you are crossing the string boundary of Overflow (str1) is why you are getting sigsegv.

str1 does not have enough memory allocated to accomodate beyond Overflow.

Upvotes: 0

Related Questions