-1

私はCから始めています。シリアルポート(ファイルではありません)から情報を取得するプログラムを作成しようとしています。シリアルポートは常に情報を送信しています。私は小さなプログラムを書きましたが、セグメンテーション違反が発生し続けました:11。主な目的は、シリアルポートから取得した情報を取得してファイルに保存することです。助けてくれてありがとう。

#include <stdio.h>   
#include <string.h>  
#include <unistd.h>  
#include <fcntl.h>   
#include <errno.h>   
#include <termios.h> 
#include <stdlib.h>
#include <unistd.h>
#include <termios.h>
#include <sys/ioctl.h>

int open_port();

main()
{

    printf("\n\nStarting...\n\n");
    open_port();

    return (1);
}

int open_port()
{
    int fd;
    int bytes;
    int string;

    char *input;


    struct termios options;

    /* open usb entry */
    fd = open("/dev/cu.usbserial-FTF6001E", O_RDWR | O_NOCTTY | O_NDELAY);


    /* check it could be opened */
    if (fd == -1)
    {
        perror("\n\nopen_port: Unable to open /dev/cu.usbserial-FTF6001E - ");
    }    
    else{

        ioctl(fd, FIONREAD, &bytes);
        printf("\n\nbytes: %d\n\n", bytes);



        fcntl(fd, F_SETFL, 0);

        /* get port options currently set*/
        tcgetattr(fd, &options);

        options.c_cflag &= ~PARENB;
        options.c_cflag &= ~CSTOPB;
        options.c_cflag &= ~CSIZE;
        options.c_cflag |= CS8;

        /* Set the baud rates to 19200...*/
        cfsetispeed(&options, B9600);
        cfsetospeed(&options, B9600);

        /* Enable the receiver and set local mode...*/
        options.c_cflag |= (CLOCAL | CREAD);

        /*Set the new options for the port...*/
        tcsetattr(fd, TCSANOW, &options);

        *input = (char) malloc (string * sizeof(char));

        if (input == 0){

            fputs("\n\nUps! Failed to allocate memory!!!\n\n",stdout);

        }

        if ( fgets (input , 100 , fd) != NULL ){
            puts (input);
            fclose (fd);
        }

        printf("input = %s", input);

    }
4

1 に答える 1

2

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

*input = (char) malloc (string * sizeof(char));

inputまず、ではなくに割り当てます*inputinputはまだどこへの有効なポインタでもないため、*input未定義の動作です。

ただし、それを修正しても、問題が発生します(a)。変数stringは初期化されていないため、プログラムの開始時にスタックにあったごみに設定されます。つまり、mallocとにかく適切な量のメモリが返される可能性は低いということです。

さらに、の戻り値を ! にキャストしていmallocますcharmallocC では( to などの)の戻り値をキャストしないでくださいchar *。これは、後で他の問題を引き起こす可能性のある特定のエラーを隠してしまうためです。

ほぼ確実に情報がchar失われるため、にキャストしないでください。明示的なキャストとは、自分が何をしているのかを知っていることをコンパイラーに伝えることです-ここではあまり正確ではないと思います:-)

実際、100バイトしか読み取っていないため、メモリを動的に割り当てている理由がまったくわかりません。を捨てて、次のようmallocに定義しますinput

char input[100];
input[0] = '\0';

(a)さらに問題があるかもしれませんが、それらは私がすぐに思いついた問題です。ただし、間違いなくセグメンテーション違反の原因であるため、最初にそれらを修正することをお勧めします。

それでも問題が解決しない場合は、別の質問に戻ってください。

于 2012-08-14T08:45:50.407 に答える