0

The following code throws an access violation at line L2 at runtime, which happens during the 2nd call to setword.

Q> Where am I going wrong in L2, and why is there no problem with the 1st memset at line L1?

Note: I have tried to isolate the problem area from a larger code, hope this provides enough info.

void setword( char ** word )
{
    if ( *word == NULL )
    {
       *word = (char *)malloc(30);
        memset( *word, '\0', 30 ); //L1: OK 
    }
    else
    {   
        memset( *word, '\0', 30 );//L2: Access violation
    }

    *word = "Hello";
    //*word shall be freed when operations are complete.
}
int main()
{
    char * word = NULL;

    setword( &word );  //Call 1: OK
    printf( "%s\n", word );

    setword( &word );  //Call 2: NOK!
    printf( "%s\n", word );
}  
VivereJay
  • 71
  • 8

2 Answers2

5
*word = (char *)malloc(30);
[...]
*word = "Hello";

The second assignment produces a memory leak (you've lost the pointer that malloc returned), and makes word point to potentially read-only memory - any write access to it will lead to undefined behavior.

(See for example this question: Is modification of string literals undefined behaviour according to the C89 standard? - in your case, "Hello" is a string literal. You make word point to that with the second assignment. So you can't modify the data that word points to afterwards.)

Use strcpy to copy "hello" to your dynamically allocated buffer.

Community
  • 1
  • 1
Mat
  • 202,337
  • 40
  • 393
  • 406
  • I would just like to add that "Hello" is the part of the program static data and probably really IS read-only memory. OP is lucky because if it wasn't he'll overwrite what's next there... – Daniel Mošmondor Aug 18 '13 at 12:33
  • Thanks a lot Mat. In my original code I was not assiging something to *word, I was actually filling it up using **word = some_char. However, I DID do some pointer arithmetic with *word, on which I lost the original *word, leading to all hell being let lose, as you have pointed out! – VivereJay Aug 18 '13 at 14:57
0

you should know that after *word = "Hello", the value of *word is constant region, you can change the content of this region.

BlackMamba
  • 10,054
  • 7
  • 44
  • 67