I am quite new to C, and I'm working on a program right now where I am asking the user to input character arrays(strings) in the form of program names, store these names in an array then pass this array to another function.
Right now, the latest way I've attempted to achieve this is with a dynamically allocated array, as I don't know what the user may want to input, and here's how I'm doing that:
char *process;
process = (char *)malloc(sizeof(char) * (i+1));
I then go on to request the user's input and confirm their input with printf:
printf("Enter process name: ");
scanf("%79s", &process); // take input, load into array
// fgets(process, sizeof(ARRAY_SIZE), stdin);
printf("You entered: %s\n", process[i]);
I've tried both scanf() and fgets(), where scanf() actually works and fgets() causes the program to jump completely past my printf statement and goes on to this:
for(i = 0; i < ARRAY_SIZE; i++)
printf("process = %s\n", process[i]);
Which is where the program terminates with a Segmentation Fault. I understand this is due to the user input overrunning the buffer allocated.
In gdb when printing the value of process, it's filled with garbage (which from my understanding is how C initializes an array before values are added). Right after scanf("%79s", &process), process shows my input added at the beginning of the garbage instead of replacing the garbage. My question is how do I "empty" my array so I quit overrunning the buffer? Been at this for three days trying several methods, and I think it has to do with me missing some detail of how to properly initialize my array. I have #define ARRAY_SIZE 80 which should be more than adequate to get this functioning, though may not suffice in later implementations.
Any help is much appreciated.
iand its value but yetscanf("%79s", &process);is wrong and has to bescanf("%79s", process);iasi = ARRAY_SIZE;. Why would I doscanf("%79s", process)as opposed to my original version, though? I thought I would want to load the input at the beginning address ofprocess. I'll pull together an MCVE for you guys, as I have several other functions that work fine in the program but make it quite long.scanf("%79s", &process)is writing in theprocessobject not in the bufferprocessis pointing to.