0

I got segmentation fault: 11 in my code, and i could not figure it out why. I got it after the second fgets.

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

typedef struct Worker {
char*  name,addr,days;
} Worker;

int main(){

printf("You chose the 1st (New Data) action\n");
printf("Please give your name (Max 20 character):  ");
int const maxNameLength = 20;
Worker worker;

char tmpName[maxNameLength];
fgets(tmpName,maxNameLength,stdin);

worker.name = (char*)malloc(sizeof(char)*(strlen(tmpName)+1));
strcpy(worker.name,tmpName);
printf("\n");

printf("Please give your address (Max 30 character): ");
int const maxAddrLength = 30;

char tmpAddr[maxAddrLength];
fgets(tmpAddr,maxAddrLength,stdin);

worker.addr = (char*) malloc(sizeof(char)*(strlen(tmpAddr)+1));
strcpy(worker.addr,tmpAddr);
printf("\n");

free(worker.name);
}

When I compile it, I get 2 warnings:

The first one:

.c:31:17(worker.addr =...): warning: assignment makes integer from pointer without a cast

Second one:

.c:32:12(strcpy(worker.addr,...): warning: passing argument 1 of 'strcpy' makes pointer from integer without a cast.

I don't really understand why those two warnings is here. Isn't the worker.addr a `char*`` ? I defined it in the struct.

However it is also strange to me, that I didn't get any warning for the first worker.addr assignment, just to the second one.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Benedek
  • 41
  • 4
  • 3
    In the `struct` member definition `char* name,addr,days;` only `name` is a pointer. Please write as `char *name, *addr, *days;` The `*` qualifies the following variable, not the preceding type, even if it is placed next to the type. So `char* name` is exactly the same as `char *name`. – Weather Vane Mar 29 '20 at 20:34
  • 1
    @Eraklon sorry to roll back the edit: your cosmetic changes had removed the confusion. – Weather Vane Mar 29 '20 at 20:37
  • 1
    @WeatherVane No hard feelings. – Eraklon Mar 29 '20 at 20:38
  • @WeatherVane thank you. Sorry, it is a basic solution, but i could not figure it out earlier. – Benedek Mar 29 '20 at 21:11

1 Answers1

1

This does not what you think it does:

typedef struct Worker {
  char*  name,addr,days;
} Worker;

it is equivalent to

typedef struct Worker {
  char *name;
  char addr;
  char days;
} Worker;

That should be enough information for you to find out what's wrong.

BTW the warnings makes integer from pointer without a cast are actually rather errors, at least in 99% of all cases. When you see this kind of warning, consider it as an error.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115