小编J.D*_*Doe的帖子

缩小char时,realloc()的行为不符合预期*

我试图用realloc()缩小指针"ptr",如下面的示例代码所示:

char * ptr = malloc(sizeof(char) * 7);
int i;
for(i = 0;i<7;i++){
    ptr[i]= "pointer"[i];
}
puts(ptr);
ptr = realloc(ptr,sizeof(char) * 3);
puts(ptr);
free(ptr);
Run Code Online (Sandbox Code Playgroud)

期望代码释放未使用的内存我认为它会返回以下内容:

pointer
poi
Run Code Online (Sandbox Code Playgroud)

但是,它会返回:

pointer
pointer
Run Code Online (Sandbox Code Playgroud)

这是编译器的错误,还是我对realloc()的理解错误?

c memory memory-management

3
推荐指数
1
解决办法
434
查看次数

fgets()在main()之外意外行为

我正在尝试在名为"a_function()"的函数中运行fgets().

int a_function(){
    char* str;
    FILE *fp;

    fp = fopen( "./file.txt", "r" );
    if( NULL != fp ){
        fgets( str, 6, fp );
        printf( "%s\n", str );
    }else{
        printf( "cannot find file\n" );
        return 1;
    }
    return 0;
}

int main(void){

    a_function();

    return 0;

}
Run Code Online (Sandbox Code Playgroud)

但是这样做会导致在调用fgets()函数时发生段错误.有趣的是,我可以将我的代码从a_function逐字复制到我的main()函数中,一切运行正常:

#include <stdio.h>
#include <stdlib.h>

int a_function(){

    return 0;
}

int main(void){

    a_function();
    char* str;
    FILE *fp;

    fp = fopen( "./file.txt", "r" );
    if( NULL != fp ){
        fgets( str, 6, fp );
        printf( "%s\n", …
Run Code Online (Sandbox Code Playgroud)

c linux stdio

3
推荐指数
1
解决办法
97
查看次数

标签 统计

c ×2

linux ×1

memory ×1

memory-management ×1

stdio ×1