Reputation: 1065
I've the following problem with this code:
#define success "success"
#define fail "fail"
char *verify = fail;
char b[1024];
int main(){
...
...connect to server code...
...
read(sock,verify,1024);
printf("%s",verify); //there's the problem, it always prints fail. If I change with this:
read(sock,b,1024);
printf("%s",b); //this works and prints the received string.
}
Can you help me to understand? The problem is in this part of this code or should I check elsewhere?
If I do an easy assign in the code like 'verify=success' it seems to works fine, reading from a socked isn't the same as an asisgnation?
Upvotes: 0
Views: 47
Reputation: 12629
You try to read from the socket into the memory area pointed by verify
, which is "fail"
.
In C the expression "fail"
allocates 5 bytes in read-only memory, fills them with {'f','a','i','l','\0'}
in compile time and returns its address.
So you're trying to overwrite read-only memory. I'm wondering why you don't get a segmentation fault. Did you check the return value of read
? It might be a kernel-side sanity check within read
which prevents it from attempting to write into RO memory.
In the second read
call, it's OK, because b
points to the start of the array variable, which is writable.
You're actually confusing yourself with your own coding style: defining fail
, which looks like a variable, does not make it a variable. The C preprocessor just replaces it and you end up with
char *verify = "fail";
Upvotes: 1