Is it possible the check the function parameter is char array, const string, string pointer to malloc data
I get some problem with the function parameter checking. There are three type of string can be parameter in func(char *str): 1. const string 2. string pointer to a malloc data 3. char 开发者_运维技巧array. It is possible to limit the c function only accept the const string, like "1111"?
I try to write some code like below, but it doesn't work.
struct test{
const char *val;
};
void func(struct test *t, const char *rodata)
{
t->val = rodata;
}
But I found I can't check which rodata I pass to func():
/* Test: rodata don't free after function call, it can be the point to*/
func(t, "333");
printf("%s\n", t->val);
/* Test: C function can't check rw char array, even with const ...*/
char rwdata[] = "22222";
func(t, rwdata);
memset(rwdata, '9', sizeof(rwdata));
printf("%s\n", t->val);
/* Test: C function can't check malloc ?*/
char *rwdata2 = strdup("rodata2");
free(rwdata);
func(t, rwdata2); /* cause error */
printf("%s\n", t->val);
}
No -- all three arguments are pointers. There is no way to reliably distinguish between them.
3rd error
you could do this way
typedef struct
{
const char* val;
}test;
test func(test t, const char* s)
{
t.val = s;
return t;
}
int main()
{
test t ={0};
char* p = NULL;
p= (char*)malloc(4);
strncpy(p, "abc", 4);
t = func(t, p);
}
精彩评论