0

作業ディレクトリをファイルに書き込むだけの簡単なプログラムを作成しようとしていますが、私の人生では、何が間違っているのかわかりません。何をしても、getcwd() を呼び出した後、バッファーに null が格納されます。私はそれが許可に関係しているのではないかと疑っていますが、伝えられるところでは、Linux は現在、 getcwd がアクセスの問題 (キーワード、「ほとんど」) をほとんど起こさないようにするためのいくつかの魔法を使っていると言われています。誰でも自分のマシンでテストできますか? それとも、私が見逃している明らかなバグがありますか?

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

int main(int argc, char *argv[])
{
        printf("Error is with fopen if stops here\n");
        FILE* out_file = fopen("dir_loc.sh","w+");
        char* loc = malloc(sizeof(char)*10000);
        size_t size = sizeof(loc);
        printf("Error is with cwd if stops here\n");
        loc = getcwd(loc,size);
        printf("%s",loc);
        fprintf(out_file,"cd %s",loc);
        printf("Error is with fclose if stops here\n");
        free(loc);
        fclose(out_file);
        return 0;
}

でコンパイルgcc main.c(ファイル名は「main.c」)

編集: さまざまなポスターで言及されているように、 sizeof(loc) は、そのポインターに割り当てられたスペースのサイズではなく、char ポインターのサイズを取得していました。それを malloc(sizeof(char)*1000) に変更すると、すべてグレービーで動作します。

4

1 に答える 1

2

あなたの問題はここにあります:

size_t size = sizeof(loc);

char に割り当てられたメモリではなく、char ポインターのサイズを取得しています。

次のように変更します。

size_t size = sizeof(char) * 10000;

または

size_t size = 10000;

sizeof(char)1 であることが保証されています。

sizeへの後続の呼び出しで を使用してgetcwdいるため、ほとんどのパスを保存するには明らかにスペースが少なすぎるため、結果は驚くべきものではありません

変更を行うたびにコード内の複数の異なる数値を変更したくない場合は、#DEFINE テキスト置換を使用して解決できます。

このような:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define LOC_ARRAY_SIZE 10000 // Here you define the array size

int main(int argc, char *argv[])
{
        printf("Error is with fopen if stops here\n");
        FILE* out_file = fopen("dir_loc.sh","w+");
        char* loc = malloc(sizeof(char)*LOC_ARRAY_SIZE); // sizeof(char) could be omitted
        size_t size = sizeof(char)*LOC_ARRAY_SIZE;
        printf("Error is with cwd if stops here\n");
        loc = getcwd(loc,size);
        printf("%s",loc);
        fprintf(out_file,"cd %s",loc);
        printf("Error is with fclose if stops here\n");
        free(loc);
        fclose(out_file);
        return 0;
}
于 2016-07-01T06:22:14.520 に答える