分配给 char* 时出现分段错误
所以我在这里编写这段代码,我只是想要一个函数返回一个字符数组并将其分配给主函数中的变量。这是返回 char* 的函数
char* getString(pid_t pid, long address, long length)
{
char* str = (char *)malloc((length+1) * sizeof(char));
int i =0;
while (i < length)
{
char t = ptrace(PTRACE_PEEKDATA,pid,address+i,0);
str[i] = t;
i++;
}
// str[length] = '\0';
printf(" Exiting getString %s \n ", str);
return str;
}
这是我在 main 中所做的
int main {
...
...
char* st = getString(pid, arguments[1], arguments[2]); // causes seg fault
// printf("getstring %s\n", getString(pid, arguments[1], arguments[2])); works fine
// and produces correct output
return 1;
}
我最近在 C 中没有做太多事情,所以也许我错过了一些东西,但为什么 printf 可以工作而分配失败?有人可以告诉我我在这里做错了什么吗?
So I'm writing this code here and I simply want a function to return a character array and assign it to a variable in main function. Here is the function returning char*
char* getString(pid_t pid, long address, long length)
{
char* str = (char *)malloc((length+1) * sizeof(char));
int i =0;
while (i < length)
{
char t = ptrace(PTRACE_PEEKDATA,pid,address+i,0);
str[i] = t;
i++;
}
// str[length] = '\0';
printf(" Exiting getString %s \n ", str);
return str;
}
And here is what I do in main
int main {
...
...
char* st = getString(pid, arguments[1], arguments[2]); // causes seg fault
// printf("getstring %s\n", getString(pid, arguments[1], arguments[2])); works fine
// and produces correct output
return 1;
}
I haven't done much in C lately so maybe I'm missing something, but why does printf works and assigning fails? Can someone tell me what am I doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您注释掉了函数中以 null 终止字符串的行。
事实上,它仅在
main()
中的一种情况下出现段错误,这只是运气(未定义的行为);您也在函数中调用printf()
。You commented out the line in your function where you null terminate your string.
The fact that it only segfaults in one case in
main()
is simply luck (undefined behavior); you're callingprintf()
in your function as well.