我在我的程序中发现了错误并决定编写一个简单的错误,这将有助于我了解正在发生的事情.这里是 :
#include <stdio.h>
#include <stdlib.h>
char * first()
{
char * word = malloc(sizeof(char) * 10);
word[0] = 'a';
word[1] = 'b';
word[2] = '\0';
return word;
}
char * second ()
{
char * word = malloc(sizeof(char) * 10);
word = "ab";
return word;
}
int main ()
{
char * out = first();
printf("%s", out);
free(out);
out = second();
printf("%s", out);
free(out);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该first()功能正常工作,但second()(确切地说free(out))发生了错误:
`.a.out'出错:munmap_chunk():无效指针:0x0000000000400714***ababAborted(核心转储)
我不明白为什么第一个功能是正确的,但第二个功能不正确.谁有人解释为什么?
fuz*_*fuz 36
在函数中second(),赋值word = "ab";指定一个新指针word,覆盖通过获得的指针malloc().当您free()稍后调用指针时,程序崩溃,因为您传递的指针free()尚未通过指针malloc().
分配字符串文字不会像您想象的那样复制其内容.要复制字符串文字的内容,请使用strcpy():
strcpy(word, "ab");
Run Code Online (Sandbox Code Playgroud)
ame*_*yCU 13
在功能上 char * second
char * word = malloc(sizeof(char) * 10);
word = "ab";
Run Code Online (Sandbox Code Playgroud)
第二个语句word = "ab";更改word为指向远离已分配的内存.您不是将字符串复制"ab"到分配的堆区域malloc.
对于free未分配malloc或类似功能的内存会导致程序崩溃.
尝试释放无效指针(指向未由calloc,malloc或realloc分配的内存块的指针)可能会影响后续分配请求并导致错误.
你应该在这里使用strcpy其他人的建议.
| 归档时间: |
|
| 查看次数: |
45281 次 |
| 最近记录: |