C code
char* get_char(int n)
{
char* p = (char*)malloc(sizeof(char)*n);
printf("%p\n", p);
strcpy(p, "hello,world,from c!");
return p;
}
void del_char(char* p)
{
free((void*)p);
}
{.compile: "logic.c".}
proc get_char(n: cint): cstring {.importc.}
proc del_char(p: cstring){.importc.}
var cs = get_char(100)
echo cs
cs = "I change this"
echo cs
del_char(cs)
E:CODEnim>nim c -r test.nim Hint: used config file 'd:Nimconfignim.cfg' [Conf] Hint: system [Processing] Hint: test [Processing] Hint: [Link] Hint: operation successful (10306 lines compiled; 0.361 sec total; 15.504MiB; De bug Build) [SuccessX]
0000000000645850
hello,world,from c!
I change this
Error: execution of an external program failed: 'e:\code\nim\test.exe '
The cs variable that you create is of type cstring. That is a pointer to something in memory. The line
cs = "I change this"
actually means: change the pointer to the address of the string "I change this".
That string is located somewhere in memory. It is a literal string, so it's unclear where it actually is pointing at. With
del_char(cs)
you are trying to deallocate (the memory behind) this pointer, which is illegal. Hence the error.
This little program also prints out the pointer values. I hope this shows what is going on ...
import strutils
{.compile: "logic.c".}
proc get_char(n: cint): cstring {.importc.}
proc del_char(p: cstring){.importc.}
var cs = get_char(100)
echo "0x", cast[int](cs).toHex(8), " : ", cs
cs = "I change this"
echo "0x", cast[int](cs).toHex(8), " : ", cs
del_char(cs)
gives
0x6a6010
0x006A6010 : hello,world,from c!
0x00423073 : I change this
Traceback (most recent call last)
test.nim(11) test
SIGSEGV: Illegal storage access. (Attempt to read from nil?)