簡體   English   中英

C: Segmentation Fault 11 strcpy 指針數組

[英]C: Segmentation Fault 11 strcpy pointer Array

代碼編譯沒有錯誤,但我得到一個分段錯誤錯誤 (11),我猜問題是當我在第 82 行中使用 strcpy() 函數時,出現問題,為什么我沒有收到任何編譯錯誤以及如何我可以修復它嗎,char 數組指針實現得好嗎?。 我無法修改代碼的當前結構。

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

請記下以下幾點並嘗試:

  1. 避免使用strcpy/strcat等。它們不能防止緩沖區溢出。

  2. 請改用strlcpy/strlcat

  3. 使用strncpy ,請確保 NULL 終止字符串緩沖區。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM