0

I have the following code.

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

int main()
{
char * l;
*l = 'c';
*(l+1) = 'g';
*(l+2) = '\0';

char *second;
strcpy(second, l);
printf("string: %s\n", second);
}

When I run it is says:
The output says "Segmentation fault"....any suggestions??

Thanks

user1684072
  • 169
  • 2
  • 7

3 Answers3

1

l is an uninitialized pointer; you can't dereference it. You should allocate enough space to write its contents (statically (1) or dynamically (2)).

char l[3]; /* (1) */

#include <stdlib.h>
char *l = malloc(3); /* (2) */

It is the same error with strcpy: second is an unitialized pointer, you can't write into it.

md5
  • 23,373
  • 3
  • 44
  • 93
  • this brings up another question? if I have char * ch; would this automatically allocate one memory location for me to store one character – user1684072 Oct 21 '12 at 09:36
  • No, if you have `char *ch`, it just allocates space to a pointer to `char`, and it remains unitialized. It you want to have a character, declare rather `char ch`. – md5 Oct 21 '12 at 09:39
0

You will learn to despise the Segmentation Fault error...

It's usually called when you try to access memory that is not yours. Most common occurrence would be when you try to access an array index that is out of bounds.

char *l just creates a pointer to a char. What you want is a string, which in C is defined as an array of chars. So when you try to access the next location in memory of whatever l is pointing to (which will probably just be garbage), you're going to access memory that isn't yours, thus Segmentation Fault

brianSan
  • 545
  • 6
  • 17
0

You could get memory with malloc or point the pointer to an already existing variable.

  char word[3];
  char *l;
  l = word;

Now you can do such assignments:

  *l = 'c';
  *(l+1) = 'g';
  *(l+2) = '\0';

but now that you want to copy it to another pointer, this pointer must be pointing to another string or you should allocate memory for it.

  char *pointer_to_second;
  char second[3];
  pointer_to_second = second;

or if you prefer to get dynamic memory, change the 3 lines above be this one bellow:

  char *pointer_to_second = malloc(sizeof(char) * 3);

after that you can do what you wanted:

  strcpy(pointer_to_second, l);

But remember, if you are using a C compiler you must declare all variables at the beggining, otherwise you will get an error. If you are using a C++ compiler you won't have to concern about it.

Segmentation fault happens when you try to access a field that doesn't belong to your vector. For example, if you try this:

  printf("The value in position 3 of my pointer is %c\n", *(l + 3));

You will probably get an error, because you pointer have 3 positions and you are trying to acess the 4th one.

vmp
  • 2,370
  • 1
  • 13
  • 17