Angus
Angus

Reputation: 12631

memcpy command in c

#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

Upvotes: 3

Views: 743

Answers (2)

Mysticial
Mysticial

Reputation: 471559

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

Upvotes: 11

DipSwitch
DipSwitch

Reputation: 5640

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;
}

Upvotes: 4

Related Questions