Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VS2010 C code - String pooling

Below code crash in VS 2010 when you compile with following flag and if you add /GF- or remove the opimization flag they don't crash. The crash occur at assembly code which translate 'if( path[i] == '/' )'. I like to understand the optimization that compiler does here and lead to crash. Looking forward for some pointers.

-Karthik

cl.exe /MD /O2 test.c

// Test.c

#include <stdio.h>

#include  <string.h>

void testpath(char* path, int bufsiz)  
{  

    int i;  

    printf("%p\n", path);  
    for( i=0; i < strlen(path); i++ ) {  
      if( path[i] == '/' ) {  
         path[i] = '\\';  
     }  
  }  
}

int main()  
{  

    const char* path = "testexport.prj";  
    char *path1 = "testexport.prj";  
    printf("%p\n", path);  
    printf("%p\n", path1);  
    testpath(path, 1024);  
}  
like image 950
Kartlee Avatar asked May 01 '26 15:05

Kartlee


2 Answers

Trying to modify the contents of a string literal invokes Undefined Behaviour.

From ISO C99 (Section 6.4.5/6)

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined

From ISO C++-98 (Section 2.13.4/2)

Whether all string literals are distinct(that is, are stored in non overlapping objects) is implementation defined. The effect of attempting to modify a string literal is undefined.

On most implementations (including MSVC) this results to crash of your application.

like image 93
Prasoon Saurav Avatar answered May 04 '26 05:05

Prasoon Saurav


You try to modify a string literal, that's undefined behavior.

 const char* path = "testexport.prj";
 testpath(path, 1024);
 // then later:
 void testpath(char* path, int bufsiz)
 {
     int i;  
     for( i=0; i`<`strlen(path); i++ ) {  
     if( path[i] == '/' ) {  
         path[i] = '\\';// <<<<<< UB here
     }  
 }  

string literals are usually stored in read-only memory, so on your implementation an attempt to modify a string literal results in access violation that crashes your program.

like image 42
sharptooth Avatar answered May 04 '26 05:05

sharptooth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!