Pelles C forum
C language => Beginner questions => Topic started by: sgraffe on March 25, 2017, 11:12:38 PM
-
Hello, friends:
I want to strip a character from a string, copying in place except the unwanted char with the following code:
// test.c
#include <stdio.h>
#include <windows.h>
void stripChar(char *s, char ch)
{
char * t;
t = s;
if (!ch) return;
while ((*s = *t++))
{
if (*s != ch) s++;
}
}
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
char *s = "This is a test";
FILE *df = NULL;
df = fopen("test.txt","a");
fputs(s, df);
stripChar(s, 'a');
fputs(s, df);
fclose(df);
return EXIT_SUCCESS;
}
The program runs, but it does not produce the expected result, a file with "This is a testThis is test". The file test.txt is empty
I started the debugger and the program does not enter the while loop. At the end of stripChar I get "Exception: Access violation"
I tried this same program in the tcc compiler and it works.
Any ideas?
-
problem is this line
char *s = "This is a test";
in PellesC it goes .rdata section and it is readonly variable.
use this in your testchar s[] = "This is a test";
-
Thank you very much, Timo.
I didn't have any idea about the .rdata section.
I did a search on that subject and found that char *s "not necessarily can be modified", and also found a reference to K&R who say that "the result is undefined if you try to modify the string contents". Since it is undefined,some compilers treat it differently For me they were completely equivalent. Well, newbie here. I also learned a little bit about the data sections and the PE format.
Thank you very much
Simon
-
I still have a question on this subject.
Why didn't the program give any error when executing? It simply stoppped with no message. I only got the access violation error when running the debugger.
Regards,
Simon
-
The behavior is dependent also on the OS you're running.
The compiler defines sections and their attributes (R/W for .data and RO for .rdata), but it is a duty of OS to enforce the attributes (the access violation is an hardware exception that need proper hardware initialization to trigger the error).
In old OS there was no difference between R/W and RO sections because the protection bits are not set in page directories. So no error were generated.
Some compiler used only a .data section for both R/W and RO data.
On actual OS the protections are enforced, and the error silently handled in standard run. In a debugging section the error is detect because of the debug mechanism.
-
I am learning something new every minute here. I thought any error would be shown by the operating system. This explains some behavior in another program that I didn't understand before.
Thank you, Frankie.
Simon