#I need help with a segmentation fault

21 messages · Page 1 of 1 (latest)

sterile citrus
#

Hey guys, I am a complete beginner and am confused as to why I keep getting a segmentation fault.

formal wyvernBOT
#

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.

sterile citrus
#

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 }
~
~
~
~
~

winged inlet
#

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

sterile citrus
#

oh ok

winged inlet
#

or allocate memory in the calling function and pass the pointer to parser

sterile citrus
#

thanks for your help :D

winged inlet
#

👍

formal wyvernBOT
#

@sterile citrus Has your question been resolved? If so, run !solved :)

sterile citrus
#

!solved

formal wyvernBOT
#

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

carmine widget
sterile citrus
#

what?

#

this language is torture

carmine widget
#

arrays decay to pointers when passed to functions

#

you need to pass the size as an argument if you need it