I am trying to write a program that reads text from a file, converts the characters to uppercase and then writes the output on a new file. The code works just fine for the reading and converting to uppercase parts, but for the writing the output part when I create a char* for the name of the output file, I get a segmentation fault.
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
void lowerToUpper(char* temp)
{
char* name;
name = strtok(temp,":");
// Convert to upper case
char* s = name;
while (*s)
{
*s = toupper((unsigned char) *s);
s++;
}
}
int main()
{
int fd;
char* file_name_read = "./test.txt";
fd = open(file_name_read, O_RDONLY);
char* buf_rd;
ssize_t nr;
size_t byte_count = 1000;
off_t offset = 0;
nr = pread(fd, buf_rd, byte_count, offset);
close(fd);
lowerToUpper(buf_rd);
char* file_name_write = "./test_uppercase.txt";
/* CODE FOR WRITING TO THE FILE */
return 0;
}
When I remove the char* file_name_write line, the code works fine. When I include it in the code, I get a segmentation fault.
I have tried
- removing the call to the
lowerToUpper()insidemain - using
char file_name_write[]instead ofchar* file_name_write - using
malloc()to allocate space and then assign its value - using different
byte_countandoffsetvalues
Edit:
The problem was an uninitialized pointer with buf_rd. When I added
char* buf_rd = (char*) malloc(1000 * sizeof(char));
it solved the problem.
Thank you Mr Lister and lurker!
preadexpects you to pass a valid buffer pointer.buf_rddoesn't hold a valid buffer pointer. It's an uninitialized pointer. Initializing it with NULL will causepreadto attempt to write to address NULL, which is bad. Unclear what "other temporary values" means in your context. And you said you have tried usingmallocbut haven't shown exactly what/how you did that.buf_rd = malloc(byte_count * sizeof *buf_rd);before callingpread