Frage

I am trying to control the ar.drone using a C program. the wrote the at commands in a text file and passed it one by one to the program. But if I try to do that using a buffer and sprintf statement I am getting an segmentation error.

My program is :

char cmd[MAX_MSG],cmd2[MAX_MSG],cmd3[MAX_MSG];
snprintf(cmd,"AT*CONFIG= %u,\"general:navdata_demo\",\"TRUE\"",seq);
sendto(sd, cmd, MAX_MSG , flags, (struct sockaddr *) &droneAddr, sizeof(droneAddr));
seq++;
snprintf(cmd2,"AT*FTRIM=%u",seq);
sendto(sd, cmd2,MAX_MSG ,flags,(struct sockaddr *) &droneAddr,  sizeof(droneAddr));
seq++;
snprintf(cmd3,"AT*PMODE= %u,2",seq);
sendto(sd, cmd3, MAX_MSG , flags, (struct sockaddr *) &droneAddr,sizeof(droneAddr));
seq++;
char cmd1[MAX_MSG];
for(i=0;i<100;i++)
{ 
cmd1[strlen(cmd1)-1] = 0x0d;//change last character from new line to carriagereturn

 snprintf(cmd1,"AT*REF=%u,290718208",seq);
 printf("%s: %s\n",argv[0],cmd1);

rc = sendto(sd, cmd1, MAX_MSG , flags,  (struct sockaddr *) &droneAddr, sizeof(droneAddr));
if(rc<0) {
    printf("%s: can not send data\n",argv[0]);
    close(sd);
    exit(EXIT_FAILURE);
    }
seq++;
nanosleep(&wait_command , NULL);
}

What is the error? Can anyone please help?

War es hilfreich?

Lösung

First issue

The prototype of snprintf is:

snprintf ( char * s, size_t n, const char * format, ... );

So all your:

snprintf(cmd, "somestring", seq);

should be changed to:

snprintf(cmd, MAX_MSG, "somestring", seq);

Second issue

char cmd1[MAX_MSG];

for(i=0;i<100;i++)
{ 
  // here cmd1 contains garbage, hence the value of strlen(cmd1) is undefined
  cmd1[strlen(cmd1)-1] = 0x0d;
}

Andere Tipps

You didn't provide a complete program but at least there is one obvious issue.

buffer cmd1 is not initialized so

 cmd1[strlen(cmd1)-1] = 0x0d;

might cause a segfault.

I guess what you wanted is

 cmd1[sizeof(cmd1)-1] = 0x0d;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top