4

When I tried to use only INT arguments, it worked perfectly, but when I try to use strings I always get "Segmentation Fault" and I don't know why. I know it might be a silly mistake, but would anyone care to explain it to me, please?

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

typedef struct cliente{
    char *nome;
    int idade;
}t_cliente;


int main(){

    t_cliente *vet;
    int qtdCliente, i, j;

    scanf("%d", &qtdCliente);

    vet=(t_cliente*)malloc(qtdCliente*sizeof(t_cliente));

    for(i=0; i<qtdCliente; i++){
        scanf("%s", vet[i].nome);
        scanf("%d", &vet[i].idade); 
    }

    for(j=0; j<qtdCliente; j++){
        printf("%s\n", vet[j].nome);
        printf("%d\n", vet[j].idade);   
        printf("\n");
    }

    free(vet);

    return 0;
}
Ana
  • 41
  • 2

1 Answers1

1
vet=(t_cliente*)malloc(qtdCliente*sizeof(t_cliente));

(and the cast is both unnecessary and unwise in C) will give you an array of structures, each containing the two fields nome and idade.

However, nome in each structure will be set to an arbitrary value so the statement:

scanf("%s", vet[i].nome);

will almost certainly attempt to write to memory that it shouldn't be writing to.

Assuming you know what the maximum size will be for the first field, you would be better off defining it as something like:

#define MAXNOME 50
typedef struct cliente{
    char nome[MAXNOME];
    int idade;
}t_cliente;

That way, the memory you will attempt to write to will at least be valid.

However, people who use scanf("%s",...) often don't realise how bad a practice it is. It can lead to buffer overflow problems since there is no way to specify a limit on the characters that will be written to the buffer. There are much safer ways to do this (get user input), such as the one found here.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • and even if some memory is allocated for the string, you need to make sure that the `scanf` doesn't read a string longer than that! – pat Nov 12 '15 at 01:27
  • 1
    @user3121023, that often introduces other problems such as what happens if you enter 60 characters then the next thing you want is an integer. I prefer line-based user input so I can tell when things begin and end, leaving `scanf`-like functionality for files where I control the format. Someone else put it better than I: "scanf stands for 'scan formatted' and there's precious few things that are *less* formatted than user input" :-) – paxdiablo Nov 12 '15 at 01:39