3
#include<stdio.h>
#include<string.h>
int main()
{
  unsigned char *s;
  unsigned char a[30]="Hello world welcome";
  memcpy(s,&a,15);
  printf("%s",s);
  return 0;
}

This is giving me a segmentation fault. Please help me fix this error

2 Answers 2

11

You need to allocate memory for s. As it stands, it's just an uninitialized pointer that (most likely) points nowhere:

unsigned char *s = malloc(16);

And as with all memory allocations, it should be freed when you're done using it:

free(s);

EDIT: The other mistake (which I overlooked) is that you need to NULL terminate after you call memcpy.

memcpy(s,a,15);
s[15] = '\0';

Alternatively, you could use strcpy(), and truncate the string to 15 characters, but you'll need to allocate enough to store all of a (including its NULL-terminator):

unsigned char a[30]="Hello world welcome";
unsigned char *s = malloc(strlen(a) + 1);   //  Allocate
strcpy(s,a);        //  Copy entire string
s[15] = '\0';       //  Truncate to 15 characters by inserting NULL.
printf("%s",s);
free(s);            //  Free s
Sign up to request clarification or add additional context in comments.

1 Comment

Bleh... too early in the morning... Fixed.
4

a is already a pointer, when you take the reference of a by &a you get the address of a instead of the address of the string. Further more you need to allocate some memory to copy the string to via malloc.

Another error is that via memcpy you copy only 15 bytes, this means that your string is not zero terminated ('\0') this results in printf() trying to print s until it reaches 0 which could never occur. So you must use strcpy, give the proper length argument or terminate the string to zero yourself.

#include<stdio.h>
#include<string.h>
int main()
{
  unsigned char *s;
  unsigned char a[30]="Hello world welcome";

  s = malloc(strlen(a) + 1); // + 1 for the 0 character
  if (s == NULL)
  {
      perror("malloc");
      exit(1);
  }

  // copy the whole string
  memcpy(s, a, (strlen(a) + 1)); // + 1 for the 0 character
  printf("%s",s);

  // copy the first 15 bytes and 0 terminate
  memcpy(s, a, 15);
  s[15] = '\0';
  printf("%s",s);

  // copy via string copy
  strcpy(s, a);
  printf("%s",s);

  free(s)

  return 0;
}

2 Comments

@Angus: DipSwitch's answer is correct, but I think you should just use strncpy instead of strcpy or memcpy for this kind of stuff.
a is not a pointer, it is an array. a and &a actually have the same value because arrays 'decay' to pointers in cirtain circumstances.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.