Can anyone tell me what’s wrong with this code? I’m getting a seg fault. I’m trying to read just the first line of a file into a newly-created file.
char *buffer;
int main(int argc, char *argv[])
{
FILE *source = fopen(argv[0], "r");
FILE *destination = fopen("destination", "w");
fgets(buffer, 500, source);
fwrite(buffer, 1, sizeof(buffer), destination);
}
You haven’t allocated anything for
buffer.Change:
to
As your code is right now,
bufferis just an uninitialized pointer. Attempting to dereference it will cause undefined behavior. (and seg-fault in your case)Alternatively, you can dynamically allocate memory for
buffer:but you should remember to free the memory later on:
If you go with this latter method, the code will look like this: