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.

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";

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.