printf() throws a segmentation fault when I pass a null-terminated string for some reason.
Here's a demonstration of my problem in GDB
λ sudo gdb -q notesearch Reading symbols from notesearch...done. (gdb) break 53 Breakpoint 1 at 0x400b32: file notesearch.c, line 53. (gdb) run Starting program: /home/frosty/hack/chapter_2/code/notesearch [DEBUG] UserID: 0 [DEBUG] File Descriptor: 3 Breakpoint 1, print_notes (fd=3, uid=0, searchstring=0x7fff3daf7fc0 "") at notesearch.c:53 53 printf("%s\n", note_buffer); (gdb) x/8xb note_buffer 0x7feb5a997168: 0x68 0x65 0x6c 0x6c 0x6f 0x0a 0x00 0x00 (gdb) x/s note_buffer 0x7feb5a997168: "hello\n" (gdb) next Program received signal SIGSEGV, Segmentation fault. _dl_fixup (l=, reloc_arg=) at ../elf/dl-runtime.c:148 148 ../elf/dl-runtime.c: No such file or directory. (gdb)
Here's the source code around the problem
int print_notes(int fd, int uid, char *searchstring){ int note_length = find_user_note(fd, uid); if (note_length == -1) return 0; // End of file char* note_buffer; read(fd, note_buffer, note_length); note_buffer[note_length] = 0; // null terminator byte if(search_note(note_buffer, searchstring)) { printf("%s\n", note_buffer); } return 1; }
char* note_buffer;
, but never allocate the memory. So when you use it, you're putting info in memory, but you have no clue where. Either allocate the memory first, or use a char array. - AntonHread()
worked fine and read the expected string. Is it because it's in another area in the memory (other than the heap) and printf can't read that certain area of the memory? - Timothy Samsonnote_buffer
. C does not require a sensible outcome - welcome to Undefined Behavior (UB). - chux - Reinstate Monica