简体   繁体   中英

Segmentation Fault (core dumped) when trying to copy array C

When i run the following Segmentation Fault... The goal is to copy the argv array to allowdip array.

char *allowdip;
int *allowdipcount;


int main(int argc, char *argv)
{
  int xer;

  allowdipcount = argc;

  for(xer=0; xer<allowdipcount; xer++) {
    allowdip[xer]=argv[xer];
  }

  for(xir=0; xir<allowdipcount -1; xir++) {
    printf("%s\n", allowdip[xir]);
  }


exit(EXIT_SUCCESS);
}

Any ideas on what I'm doing wrong?

UPDATE

Thanks, now my code is:

char **allowdip;
int allowdipcount;

int main(int argc, char *argv)
{
  int xer;
  int xir;

  allowdipcount = argc;
  char **allowdip = malloc(allowdipcount * sizeof(char*));
  for(xer=0; xer<argc; xer++) {
      allowdip[xer]=argv[xer];
  }

    for(xir=1; xir<allowdipcount; xir++)
    printf("%s\n", allowdip[xir]);
    exit(EXIT_SUCCESS);

}

it returns:

 testscript2.c:51: warning: assignment makes pointer from integer without a cast

the line 51 contains:

 allowdip[xer]=argv[xer];

allowdip is an uninitialised pointer. You need to allocate memory for it

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
  int xer;
  int allowdipcount = argc;
  char **allowdip = malloc(allowdipcount * sizeof(char*));

  for(xer=0; xer<allowdipcount; xer++) {
      allowdip[xer]=argv[xer];
  }

  for(xer=0; xer<allowdipcount; xer++) {
    printf("%s\n", allowdip[xer]);
  }
  free(allowdip);
  return EXIT_SUCCESS;
}

Note that I've made a few other changes in your code

  • allowdipcount should be of type int (otherwise you need to allocate storage for it too)
  • allowdip has changed type to be an array of char pointers
  • the signature of main wasn't quite right - argv should be a char* array
  • Changed your global variables to be local to main since there wasn't an obvious need for them to be global
  • Changed the printf loop to iterate over all program arguments. It was skipping the final arg in your question.
  • freed the memory we allocated for allowdip once we're finished with it
  • Simplified return from main as suggested by Vincent

You're not allocating memory, and your types are all wrong.

The counter should be an integer, not a pointer:

int allowdipcount;

and the array should be an array of pointers, not of characters:

char **allowdip;

Then you can allocate:

allowdip = malloc(argc * sizeof *allowdip);

and copy the array:

memcpy(allowdip, argv, argc * sizeof *allowdip);

Note that this doesn't copy the actual argument strings, only the array of pointers to strings. It also doesn't include the NULL pointer at argv[argc] which terminates the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM