10
I’m getting the following error message in my code:
Segmentation fault (core dumped)
Another thing is, when I performed the same function operation preenche in the main, using ficha.name in place of dados, the system printed only the first letter.
Why is the string not printed whole? And why do I get the error when using the function?
#include<stdio.h>
#include<stdlib.h>
typedef struct{
char *name;
char *phone;
char *city;
char *state;
}ficha_t;
void aloca (char *ptr){
ptr = (char*) calloc (1, sizeof(char));
if(ptr == NULL){
puts("** Memória Insuficiênte **");
exit(0);
}
}
char *preenche (){
char *dados;
int i = 0;
do{
aloca(dados);
dados[i] = getchar();
i++;
}while(dados[i] == '\n');
dados[i] = '\0';
return (dados);
}
int main(int argc, const char *argv[])
{
ficha_t ficha;
ficha.name = preenche();
printf("%s", ficha.name);
return 0;
}
On which line does segfault occur?
– Vinícius Gobbo A. de Oliveira