McqMate
RK Khadgaokar
2 years ago
I'm creating a menu-driven program where users can enter choices and data. I've implemented fgets() for safety, but after the first input, subsequent calls seem to fail or behave oddly. Here's what I've tried:Using fgets() with a buffer size of 100.Checking for NULL returns, but it doesn't help.The issue occurs especially after using scanf() earlier in the code. I suspect buffer issues, but I'm not sure how to fix it cleanly.
Pranay Gade
1 week ago
I'm working on a project where I need to store multiple strings using dynamic memory allocation. I'm using malloc to allocate an array of char pointers, then allocating each string with strdup. After processing, when I call free on the array and each string, it crashes with a segmentation fault. Here's a simplified version of my code:char **arr = malloc(3 * sizeof(char *)); arr[0] = strdup("hello"); arr[1] = strdup("world"); arr[2] = strdup("test"); // ... do something ... for (int i = 0; i < 3; i++) { free(arr[i]); } free(arr);I've compiled with -g and used gdb, but I'm not sure if I'm freeing in the right order or if there's a memory corruption issue. Any tips?
Emily Davis
1 week ago
I'm a beginner working on a project for my C programming course. I tried using scanf("%s", name); to read the name, but it stops at whitespace. I then switched to fgets(name, 100, stdin); which reads the entire line, but it leaves a newline character in the string. I've attempted to trim it with a loop, but it's messy. Could you advise on a clean solution for basic C programs?
Maria Garcia
1 week ago