I'm curious as to why the following trivial example does not work:

file: new.c

#include "new.h"

void test( char * x )
    free( x );

file: new.h

void test( char * );

file: weird.c

#include "new.h"

int main( void )
    char * strange = "this is strange";
    test( strange );
    return 0;

matt@Ragnarok ~/Code/C $ gcc -c new.c
matt@Ragnarok ~/Code/C $ gcc -o weird weird.c new.o
matt@Ragnarok ~/Code/C $ ./weird
*** glibc detected *** ./weird: free(): invalid pointer: 0x0804847c ***

What would I have to do if I wanted to do something like this? I get the same kind of problem if I do x[3] = 'c'; or *( x + 3 ) = 'c'.

I think it's just some fundamental misunderstanding and someone can set me straight. Thanks.

9 Years
Discussion Span
Last Post by Salem

What's so weird about trying to free something you didn't malloc ?

> I get the same kind of problem if I do x[3] = 'c'; or *( x + 3 ) = 'c'.
Because "string constants" on your system are in read-only memory. So ANY attempt at all to try and modify them results in instant segfault and death for your program.

If you want a string you can change, then do char strange[ ] = "this is strange";

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.