为什么 strcat 函数给我一个分段错误?
Why does the strcat function give me a segmentation fault?
我想连接“/bin/”和"touch",这样我就会有“/bin/touch”。
在我的程序中,我有
char* filePath = malloc((strlen("/bin/") + strlen(rv[0]))* sizeof(char));
filePath = strcat("/bin/",rv[0])
首先,rv[0] 包含一个字符串,"touch"。我使用 malloc 函数在内存中分配了 10 个字节,filePath 将是指向这 10 个字节内存的指针。因为,连接的字符串 ("/bin/touch") 的总长度将是 10.
程序正常执行,直到第二行出现分段错误。我在 strcat 函数上有什么错误吗?
看看 reference 如何使用 strcat
:
char *strcat( char *dest, const char *src );
Appends a copy of the null-terminated byte string pointed to by src
to the end of the null-terminated byte string pointed to by dest
.
因此,第一个参数必须是一个指针,指向一个足够大的内存位置,以容纳已经存在的 C 字符串和 src
指向的 C 字符串的字节。
您调用 strcat("/bin/",rv[0])
并因此尝试写入存储字符串文字“/bin/”的内存..通常在只读内存中,因此您遇到了分段错误。
您需要先将 "/bin/"
复制到 filePath
指向的已分配内存中,然后将 rv[0]
附加到那里。
我想连接“/bin/”和"touch",这样我就会有“/bin/touch”。
在我的程序中,我有
char* filePath = malloc((strlen("/bin/") + strlen(rv[0]))* sizeof(char));
filePath = strcat("/bin/",rv[0])
首先,rv[0] 包含一个字符串,"touch"。我使用 malloc 函数在内存中分配了 10 个字节,filePath 将是指向这 10 个字节内存的指针。因为,连接的字符串 ("/bin/touch") 的总长度将是 10.
程序正常执行,直到第二行出现分段错误。我在 strcat 函数上有什么错误吗?
看看 reference 如何使用 strcat
:
char *strcat( char *dest, const char *src );
Appends a copy of the null-terminated byte string pointed to by
src
to the end of the null-terminated byte string pointed to bydest
.
因此,第一个参数必须是一个指针,指向一个足够大的内存位置,以容纳已经存在的 C 字符串和 src
指向的 C 字符串的字节。
您调用 strcat("/bin/",rv[0])
并因此尝试写入存储字符串文字“/bin/”的内存..通常在只读内存中,因此您遇到了分段错误。
您需要先将 "/bin/"
复制到 filePath
指向的已分配内存中,然后将 rv[0]
附加到那里。