简体   繁体   English

C: Segmentation Fault 11 strcpy 指针数组

[英]C: Segmentation Fault 11 strcpy pointer Array

The code compiles with no errors, but I get a segmentation Fault Error (11), I'm guessing the problem is when I use the strcpy() function in line 82 ,something goes wrong, why im not getting any compile errors and how can I fix it, are the char array pointers well implemented?.代码编译没有错误,但我得到一个分段错误错误 (11),我猜问题是当我在第 82 行中使用 strcpy() 函数时,出现问题,为什么我没有收到任何编译错误以及如何我可以修复它吗,char 数组指针实现得好吗?。 I can not modiffy the current structs of the code.我无法修改代码的当前结构。

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

typedef struct
{
  int n_uea;
  char **nombre;
  double *calificacion;
} UEA;

typedef struct
{
  int n_pais;
  char *nombre[50];
} PAIS;

typedef struct
{
  char nombre[50];
  UEA uea;
  PAIS *pais;
} ALUMNO;

void AllocPais(PAIS *p, int np){
  p = (PAIS*) malloc(sizeof(PAIS));
  p = &p[0];
  p->n_pais = np;
  for (int i = 0; i < np; i++) {
    p->nombre[i] = (char*) malloc(sizeof(char)*50);
  }
}
void AllocUEA(UEA *u , int nu){
  u->n_uea = nu;
  u->nombre = (char **) malloc(sizeof(char*)*nu);
  for (int i = 0; i < nu; i++) {
    u->nombre[i] =(char*) malloc(sizeof(char)*50);
  }
  u->calificacion = (double*) malloc(sizeof(double) * nu);
}
void AllocAlumnoMemory(ALUMNO *a, int np, int nu){
  AllocPais(a->pais,np);
  AllocUEA(&(a->uea),nu);
}

int main(int argc, char const *argv[]) {
  ALUMNO* arreglo;
  int entradas;
  printf("%s\n","Ingrese el numero de Entradas");
  scanf("%d",&entradas);
  arreglo = malloc(sizeof(ALUMNO)*entradas);
  for (int i = 0; i < entradas; i++) {
    char separator[10];
    char name[20];
    int numUea , numPaises;
    printf("%s\n","Se espera separador");
    scanf("%s",separator);
    printf("%s\n","Ingrese el nombre");
    scanf("%s",name);
    strcpy(arreglo[i].nombre,name);


    printf("%s\n","Ingrese el numero de UEA");
    scanf("%d",&numUea);
    AllocUEA(&arreglo[i].uea,numUea);
    for (int a = 0; a < numUea; a++) {
      char name [15];
      double cal;
      scanf("%s %lf", name, &cal);
      strcpy(arreglo[i].uea.nombre[a],name);
      arreglo[i].uea.calificacion[a] = cal;
    }

    printf("%s\n","Ingrese Numero de paises");
    scanf("%d",&numPaises);
    PAIS nuvp;
    arreglo[i].pais = &nuvp;
    AllocPais(arreglo[i].pais,numPaises);
    for (int b = 0; b < numPaises; b++) {
      char names [15];
      scanf("%s",names);
      strcpy(arreglo[i].pais->nombre[b],names);
    }

  }


  return 0;
}

Please note down below points and try them:请记下以下几点并尝试:

  1. Avoid using strcpy/strcat etc. they do not protect against buffer overruns.避免使用strcpy/strcat等。它们不能防止缓冲区溢出。

  2. Use strlcpy/strlcat instead.请改用strlcpy/strlcat

  3. When using strncpy , make sure to NULL terminate the string buffer.使用strncpy ,请确保 NULL 终止字符串缓冲区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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