CLEO Help using alloc in a function

CLEO related
Status
Not open for further replies.

Hackz0r

Active member
Joined
Oct 31, 2016
Messages
25
Reaction score
0
how do I properly use "alloc" and "free" inside a function? I am trying to return a string using the function, but when I free the allocated memory inside the function it returns random letters and symbols. It works if I don't free the memory in the function, but is this is a bad way?


So for example:

Code:
while true
    wait 0
    if 
    key_down 80 //P
    then
        call @getString 0 0@
        chatmsg "%s" -256 0@
        wait 500
    end
end

:getString
alloc 0@ 64
format 0@ "i like pizza"
free 0@
ret 1 0@
 
Joined
Dec 31, 2015
Messages
712
Reaction score
27
In this code you literally erasing this string before returning
As I remember all variables inside a function will be freed after returning, so you shouldn't really care about it
 

monday

Expert
Joined
Jun 23, 2014
Messages
1,127
Solutions
1
Reaction score
158
you could just allocate the memory from the outside and pass the variable (keep in mind that once you allocate memory at some variable it becomes a pointer and can be treated like a pointer, you can add to it, substract or pass it to a function without a need to allocate the memory from inside of the function again). Btw "chatmsg" is "0AF8: samp add_message_to_chat 1@ color 2@" and it doesn't allow string formatting

Code:
alloc 0@ 64

while true
    wait 0
    if
    key_down 80 //P
    then
        call @getString 1 0@ _returned 0@
        chatmsg 0@ -256
        wait 500
    end
end

:getString
format 0@ "i like pizza"
ret 1 0@
 
Joined
Feb 18, 2005
Messages
2,965
Reaction score
271
Use the string in the func., and keep alloc/free inside the func. too.
Or you could use a global array of string, and return the element id only. 

monday said:
. Btw "chatmsg" is "0AF8: samp add_message_to_chat 1@ color 2@" and it doesn't allow string formatting

0AF8 allows string formatting, you can pass arguments to it.
Code:
0AF8: "My name is %s, and i'm %d years old"  color -1 name "Spring" age 12
 
Status
Not open for further replies.
Top