user1840255
user1840255

Reputation: 287

C Segmentation fault error on print

In the following code with the printf() statement I get a segmentation fault: 11. Without it I do not get any of errors but I want to be able to see the correct values are in the newstring value. How do I go about doing this?

  char* newstring;
  for(int i = 0; i < len; i++)
  {
    printf("value %d\n", tempfullstring[i]);
    if (tempfullstring[i]>=97 && tempfullstring[i] <=122)
    {
      char value = tempfullstring[i];
      newstring += value;
    }
  }
  printf("The new string is %s", newstrng);
  return 0;

Upvotes: 1

Views: 4642

Answers (3)

75inchpianist
75inchpianist

Reputation: 4102

this is the code you'll want to make this work.

 char* newstring = malloc (sizeof(char)*len+1);   // this will be worst case (all are >=97 o <=122
    int j=0;
      for(int i = 0; i < len; i++)
      {
        printf("value %d\n", tempfullstring[i]);
        if (tempfullstring[i]>=97 && tempfullstring[i] <=122)
        {
          char value = tempfullstring[i];
          newstring[j]= value;
          j++;
        }
      }
      newstring[j]='\0';
      printf("The new string is %s", newstrng);
      return 0;

Upvotes: 1

Jack
Jack

Reputation: 133639

newstring += value

You are appending to a string in an illegal way, what you are actually doing is changing an uninitialized pointer, so you are moving an changing address to another invalid address instead.

You should, first of all, have some room in which you are going to store the new string such with

char newstring[64];

and then append a character by doing

newstring[j] = tempfullstring[i];

This won't append the NUL terminating character through, you will have to add it to the end manually or use a different approach (such as using strncat and append directly from the original string:

strncat(newstring+j, tempfullstring+i, 1);

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

I think you have a misunderstanding of how C strings work:

  • They do not get initialized on declaration (so char* newstring; must be assigned separately, or you get undefined behavior)
  • They cannot be concatenated with a += operator (so newstring += value; is invalid)
  • The space for C strings needs to be managed explicitly (so you would either need to allocate your newstring in the automatic storage area, or add a free at the end).

The easiest way of fixing your program is to guess how long the newstring is going to be, and use strcat to append data to it:

char newstring[1000]; // some max length
newstring[0] = '\0';  // make it an empty string
...
strcat(newstring, value); // instead of newstring += value

Upvotes: 2

Related Questions