I am a 52-year-old chemical engineer who decided to change carrier, after some period of unemployment, to programming and made a mistake to choose C language to learn. In addition, English is not my native language, so be kind.
I am following "Illustrating C" by Donald Alcock. I am stuck with this problem for some time. It is a program called backslang on p105. I do not want to post the whole code, with the header file which includes custom string functions, it is about 250 SLOC.
if (Qu == Instr(p, "qu", Equiv))
{
*(Qu+1)='$';
}
What it supposed to do is: If it finds "qu"
in a string it will change the segment to "q$"
. However, char *Qu
pointer is declared inside the main() and not initialized. gcc -Wall
gives warning about it. I tried to initialize it with char *Qu = NULL
the behavior of code and error does not change. I traced it with GDB. The value of Qu is always 0x0 and when Instr function cannot find "qu" segment in string it enters to if block (0 == 0; TRUE or 1) and gives SEGMENTATION FAULT.
After a lot of research, I learned the difference between heap and stack. I have also learned that, in this kind of situation, I have to reserve memory on the heap using malloc(). However, at this point, the book has not reached to the point for that kind of knowledge and this code is supposed to work. Is this because of different C standard? The book was written in 1992. I tried the -ansi
and -std=c89
options without success. I still couldn't figure it out. What am I missing?