Reputation: 373
I have the following code:
struct argument {
char *source;
char *destination;
int value;
};
int main(void){
struct argument *arg2 = malloc(sizeof(struct argument));
strcpy(arg2->source, "a1"); //This gives segmentation fault.
strcpy(arg2->destination, "a2");
arg2->value = 1500;
return 0;
}
The problem is that when i use strcpy with arg2->destination, everything runs fine, but as soon as I uncomment the strcpy with arg2->source, I immediately get a segmentation fault. What is wrong? Is there a way to fix this?
Upvotes: 1
Views: 676
Reputation: 12354
with this statement struct argument *arg2 = malloc(sizeof(struct argument));
you allocate the memory for the structure itself. The struct contains the following fields:
struct argument {
char *source; // << a pointer to a character string
char *destination; // << another pointer
int value; // integer value
};
Next you are trying to copy a string, using one of the pointers: strcpy(arg2->source, "a1");
. But ... there is no place for the string in memory. You allocated place for the pointer (a part of the struct) but not for the string which it would point to. It causes memory corruption and your crash.
So, before copying the string, allocate some place for it:
arg2->source = malloc(3);
you need '3' which is 1 char longer than the length of the string 'a2'.
same for the other string.
You do not need to do anything extra for the value
. It is not a pointer but a part of the struct, which have already allocated.
Upvotes: 2
Reputation: 2982
You're a victim of the all-too-famous undefined behavior. You see, when uninitialized pointers are used in calls to strcpy
, there's no guarantee that it will work nor that it will throw an error. Basically, anything can happen, it can even work as expected sometimes, which makes this type of bug even more tedious to find and correct.
You need to allocate memory for your source
and destination
pointers before using them, you can use malloc(strlen("someString") + 1);
. And don't forget to release the memory when you're done by calling free
. Adopting this habit early on will free you in the future of some very nasty bugs, and more undefined behavior.
Upvotes: 4