Danilo Mitrovic
Danilo Mitrovic

Reputation: 13

pointer to structure argv assignment

I've been trying to assign argv[x] to structure pointed to by variable. I wrote following code and getting Segmentation fault, which I know is a memory violation. I do not understand where I have made a mistake. Here is the code:

#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
typedef struct somestruct {
   char name[20];
   char surname[20];
   char misc[4056];
} somestruct;


int
main(int argc, char *argv[])
{
   somestruct *pvar;
   pvar = malloc(sizeof(somestruct));
   if (pvar==NULL)
      printf("malloc failed with: %s\n", strerror(errno));
   pvar = (somestruct *)  memset(pvar, 0, sizeof(somestruct));

   memcpy((char *) &(pvar->name), argv[1], 20);
   memcpy((char *) &(pvar->surname), argv[2], 20);
   memcpy((char *) &(pvar->misc), argv[3],4056);

   return 0;
} 

Thank you in advance.

Upvotes: 1

Views: 857

Answers (1)

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58281

Correct your code, remove & in memcpy:

   memcpy((char *) (pvar->name), argv[1], 20);
   memcpy((char *) (pvar->surname), argv[2], 20);
   memcpy((char *) (pvar->misc), argv[3],4056);

Additionally you are coping to pvar from argv. the syntax of memccpy is:

void *memcpy( void *to, const void *from, size_t count );  

Where count characters from the array from to the array to.

So

  • third argument in memcpy function should be length of argv[i] but not 20, 20, 4056,
  • Also add null '\0'.

Do like:

   memcpy((char *) (pvar->name), argv[1], strlen(argv[1]));
   pvar->name[strlen(argv[1]) + 1] = '\0';
   memcpy((char *) (pvar->surname), argv[2], strlen(argv[2]));
   pvar->surname[strlen(argv[2]) + 1] = '\0';
   memcpy((char *) (pvar->misc), argv[3],strlen(argv[3]));
   pvar->misc[strlen(argv[3]) + 1] = '\0';

Upvotes: 5

Related Questions