pol*_*nux 1 c string segmentation-fault
int main(int argc, char **argv){
char *str = argv[1];
size_t len = strlen(str);
char *dst = calloc(len+1, sizeof(char));
int i;
for(i=len-1; i>=0; i--){
memcpy(dst, str+i, 1);
dst++;
}
*(++dst) = '\0';
printf("%s\n", dst);
free(dst);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
省略错误检查以获得更多可读性
我不明白为什么我得到了一条带有此消息的段错误:"glibc free():无效指针:"
我正在尝试编写一个使用指针反转字符串的小程序但是:
1) last printf什么都不打印;
2)我遇到了段错误
你有:
char *dst = calloc(len+1, sizeof(char));
/* ... */
*(++dst) = '\0';
/* ... */
free(dst);
Run Code Online (Sandbox Code Playgroud)
您必须free是由malloc/ 分配的指针calloc.在这里你修改了它.制作它的副本,以便您可以使用free它.
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |