#I need help with a segmentation fault
21 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.
1 #include <stdio.h>
2
3 char* parser(char input[]){
4
5 for (int it0 = 0; it0 < sizeof(input); it0++){
6 printf("%s",input[0]);
7 }
8
9 return &input;
10 }
11
12 int main() {
13 printf("Welcome to C-calc\n");
14
15 for (int it0 = 0; it0 == 0;){
16 printf("\033[0;31m");
17 printf("Ready... ");
18 printf("\033[0m");
19
20 //Getting user input
21 char userInput[100];
22 scanf("%s", userInput);
23
24 parser(userInput);
25
26 }
27 }
~
~
~
~
~
You're returning a pointer to the input array form the parser function
But the input array is local to that function, so once the function returns, the memory is freed
Accessing it later in the program causes the segfault
return a copy of the string instead of a pointer
or use a static or global array instead of a local one
make input a parameter so the calling code can pass in a pointer to allocated memory
oh ok
or allocate memory in the calling function and pass the pointer to parser
thanks for your help :D
👍
@sterile citrus Has your question been resolved? If so, run !solved :)
!solved
Thank you and let us know if you have any more questions!
This thread is now set to auto-hide after an hour of inactivity
sizeof(input) doesn't give you the length of the array