I can't think of situation or coding example when a string might get accidentally modified. Can someone point me in the right direction.
Chad
I can't think of situation or coding example when a string might get accidentally modified. Can someone point me in the right direction.
Chad
char foo[10];
char bar[] = "this is a test";
strcpy( foo, "this is a long message" );
This may or may not cause bar to change unexpectedly.
char bar[] = "this is a test";
char foo[10];
strcpy( foo, "this is a long message" );
This may or may not cause bar to change unexpectedly.
the best example for you is the strtok fucntion which actuall modifies the string. a sample code might make u clear
ssharish2005Code:#include<stdio.h> #include<string.h> int main() { char str[15]="hello world"; char temp[15]; char *p; strcpy(temp,str); if((p = strtok(str," "))!=NULL) printf("%s\n",p); printf("%s\n",str); <--- the original string is changed here printf("%s\n",temp); <-- the backup string is not changed getchar(); return 0; } /*myoutput hello hello hello world */
Most common is buffer overflow, attempting to copy more characters into a buffer than the buffer can hold. Salem's first example is a good example. It can happen also with functions such as strcpy(), scanf(), fscanf(), and gets() -- none of these have any limits at all on the size of character buffers.Originally Posted by cdalten
On salem's example:
char bar[] = "this is a test";
char foo[10];
strcpy( foo, "this is a long message" );
This may or may not cause bar to change unexpectedly.
How can "this is a long message" impact bar?
Well if bar[] immediately follows foo[] in memory, then overstepping foo will start writing in bar.
Most compilers allocate variables pretty close to one another, but the exact ordering and space between them obviously varies from one compiler to another (and even with different compiler options).
As Salem has said, it might impact bar if bar is adjacent to foo in memory.
But also keep in mind, if bar is not adjacent to foo in memory, that buffer overflow (writing far too many characters into a too small buffer) will stomp on whatever memory *is* adjacent to foo, and that can cause wildly unexpected results -- and not necessarily right there in that part of the code.
That's when your job as a programmer gets REALLY interesting...
So beginneth the lesson "why does my debug code work and my release code doesn't".