Reputation: 335
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);
}
Upvotes: 2
Views: 238
Reputation: 16597
You should allocate memory to store the data. It can be either statically allocated using arrays
or dynamically allocated using malloc()
#define BUFLEN 50
/* static allocation */
char buffer_array[BUFLEN];
/* dynamic allocation */
char * buffer_ptr = NULL;
if ((buffer_ptr = (char *)malloc((int)sizeof(char) * BUFLEN)) == NULL) {
printf("ERROR: unable to allocate memory \n");
return 0;
}
and here you can pass either buffer_array
or buffer_ptr
to fgets()
and fwrite()
But all the dynamically allocated memory must be free()
'ed as follows.
free(buffer_ptr);
Upvotes: 0
Reputation: 471229
You haven't allocated anything for buffer
.
Change:
char *buffer;
to
char buffer[500];
As your code is right now, buffer
is 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
:
buffer = (char*)malloc(500 * sizeof(char));
but you should remember to free the memory later on:
free(buffer);
If you go with this latter method, the code will look like this:
char *buffer;
int main(int argc, char *argv[])
{
FILE *source = fopen(argv[0], "r");
FILE *destination = fopen("destination", "w");
// Allocate
buffer = (char*)malloc(500 * sizeof(char));
fgets(buffer, 500, source);
fwrite(buffer, 1, 500 * sizeof(char), destination); // Fixed here
// Free memory
free(buffer);
// Don't forget return value
return 0;
}
Upvotes: 6
Reputation: 23868
Your buffer has no size - its a pointer to char array. You need to malloc some space to read into
Upvotes: 4