简体   繁体   中英

Deleting a character array after using strcat causes a seg fault

In my code I am using system() to call a function that exists only on the raspberry pi's shell, specifically "raspistill"

When doing this, I use a char[] and strcat() as follows:

#include <stdlib.h> 

int main(int argc, char * argv[]){
  if(argc != 2) return -1;
  char command[] = "raspistill -o ";
  strcat(command, argv[1]);
  system(command);
  delete[] command;
  return 0;
}

I get a warning saying that the length to be deleted is 15, the initial length when initializing command, instead of the new length after the strcat function.

This problem goes away when I use a C++ string with append() instead. Why does this cause a seg fault and how can I avoid it?

This isn't really C++. If you replace the

delete[] command;

with

free(command);

then you will get a C program. It will still be a buggy program however - my point is that there is very little C++ in your program.

The problem would be solved if you did fully embrace C++. In modern C++, you don't use [] arrays for anything (except in certain very special cases). If you want a collection of characters, where you can add and remove characters at will, then just use a string .

#include <string>
using std::string; 

int main(int argc, char * argv[]){
  if(argc != 2) return -1;
  string command = "raspistill -o ";
  command.append(argv[1]);
  system(command.c_str()); // unfortunately, system() doesn't accept string
                           // directly, must convert to pointer with .c_str()
  return 0;
}

You don't need to delete in well written (modern) C++. In fact, it would be a serious bug to attempt to delete command (or delete &command ) here.

Don't use pointers (except std::shared_ptr and std::unique_ptr where you really want the 'action-at-a-distance' behaviour). Don't use new , and don't use delete .

Sorry if this doesn't answer your original question directly. But I feel that just jumping straight to C++ is the best approach in situations like this.

You are trying to invoke strcat on a char[] to which you assigned a constant string literal. This will fail. Also, there is no reason for you to delete[] the aforementioned command , as you are not dynamically allocating it on the free store (eg using new[], malloc, etc.)

Edit: The following was relevant to a previous revision of the question

You're missing the new[] to go with the delete[] . The code you just posted shouldn't even be compiling, as you do not define name anywhere.

Buffer overrun I presume. command is not long enough. You're corrupting the stack. And worse you're using delete on memory that wasn't allocated on the heap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM