【发布时间】:2017-05-09 05:05:48
【问题描述】:
我的 osx 版本是 10.12,
当我从原始字符串复制字符串,然后释放它,它不工作,
但是在linux(centos 6.2)下没问题,我打印的副本无效。
找不到原因,真的很困惑。
代码如下:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(){
char *copy;
char *origin = "tutorialspoint";
copy = (char *) malloc(15);
strcpy(copy, origin);
free(copy); //not working
printf("string = %s, Address = %u\n", copy, copy);
printf("origin = %s, Address = %u\n", origin, origin);
return(0);
}
最奇怪的是当我为origin释放内存时,副本的内存也被释放了
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(){
char *copy;
char *origin = "tutorialspoint";
copy = (char *) malloc(15);
strcpy(copy, origin);
free(origin); //working for copy too
printf("string = %s, Address = %u\n", copy, copy);
printf("origin = %s, Address = %u\n", origin, origin);
return(0);
}
【问题讨论】:
-
这个程序中有很多未定义的行为。
-
代码非常错误,但它并不是真正的重复。答案需要更进一步。