Stefano Sasso
Stefano Sasso

Reputation: 3

Segfault while copying string

I'm trying to learn C, and now I'm playing with structures. I have the following piece of code:

#include <string.h>

struct user {
  unsigned int utime;
  char *username;
};

void main()
{
  char username[] = "root";
  struct user *u;
  strcpy(u->username, username);
}

But, when I try to run it, it generates a Segmentation fault. What's wrong with it?

Upvotes: 0

Views: 130

Answers (5)

Arvind
Arvind

Reputation: 478

In parallel, you should also know about memory layout, and try reasoning what lives where. A starting point for this would be -Stanford Pointers pdf I would suggest,when you are learning and get stuck,try drawing the flow, memory access on paper and then go into the debugger. I didn't do this when I learnt C first- Memory Visualization is a trait that seeems to make a person a better programmer/debugger- from what I have learnt from my colleagues/ read several articles online.

Upvotes: 0

Sudhakar B
Sudhakar B

Reputation: 1563

Two things

you have not allocated for the structure variable "struct user *u;"

and also you have not allocated memory for *username in the structore

To work

 #include <string.h>
 struct user {
 unsigned int utime;
 char *username;
 };

 void main()
 {
    char username[] = "root";
    struct user *u=malloc(sizeof(struct user));
    u->username=malloc(strlen(username)+1);
    strcpy(u->username, username);
}  

Please ignore if it has any syntax errors

Upvotes: 0

lucaboni
lucaboni

Reputation: 2424

another way would be to use u as a simple variable: struct user u; and then access to utime or username with the ".", like this:

u.utime = ...;
u.username = ...;

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409206

The first thing you should do when getting a crash (like segmentation fault), is to run your program in a debugger. It will help you pinpoint the location of the crash, and also let you examine variables to see what might have caused the crash.

However, in your case it's very simple:

struct user *u;
strcpy(u->username, username);

You haven't allocated memory for u or u->username, which means that u can point to anywhere in memory and the same for u->username.

Upvotes: 2

simon
simon

Reputation: 1145

u is a pointer to a struct but you didn't allocate any memory for it yet. The line must be struct user *u = malloc(sizeof(struct user)). Additionally you will also have to allocate memory for the username pointer within your struct before calling strcpy.

Upvotes: 3

Related Questions