strcat会覆盖我的字符串

Sam*_*Sam 2 c unix strcat

我无法弄清楚这一点.当我在我的Windows机器上使用Code :: Blocks编译这段代码时,它运行得很好,但是当我尝试使用Cygwin下的Make或者在学校的实际Unix机器上编译它时,我得到了下面的奇怪行为.我将"client1.txt"传递给translate().

void translate(char* filepath){

  char output_filepath[181];
  strcpy(output_filepath, filepath);
    printf("%s\n", output_filepath);      //this prints out "client1.txt" which is correct
  char* ptr = strcat(output_filepath, ".translated");
    printf("%s\n", output_filepath);      //this prints out ".translated" which is wrong
    printf("%s\n", ptr);                  //also prints out ".translated" wrong again

...more stuff...
}
Run Code Online (Sandbox Code Playgroud)

当尝试在output_filepath上使用fgets时,这会导致分段错误.有谁知道发生了什么?我需要解释更多吗?它必须能够在Unix下编译.

这是整个程序,我希望它不会太长.这是我老师给我们工作的一个程序,但我甚至无法让它运行.它只是给我一个分段错误,我已经跟踪了上面的部分.

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

struct tparam{
int tid;
};

int NTHREADS  =  5;
#define LOOPS         10000
int qfilled = 0;
int qin = 0;
int qout = 0;
char queue[3000][2][161];
char dic[7000][2][161];
int dic_size = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t flag_mutex = PTHREAD_MUTEX_INITIALIZER;

char * dummystatus[10];

char * lookup(char * word)
{
int i;
for(i = 0; i < dic_size; ++i)
{
    if(strcmp(word, dic[i][0])==0)
        return dic[i][1];
}
return word;
}
void translate(char filepath[])
{
char output_filepath[181];
strcpy(output_filepath, filepath);
strcat(output_filepath, ".translated");

FILE * client_file = fopen(filepath,"r");
FILE * translated_client_file = fopen(output_filepath,"w");
char line [161];
char * tmpPtr;
char * token;
while((tmpPtr=fgets(line, 160, client_file))!= NULL) {
    if(strcmp(line,"\n") == 0 || line == NULL)
        continue;
    token = strtok_r(line, " \t\n", dummystatus);

    while(token != NULL && strcmp(token,"\n") != 0){
        fputs(lookup(token), translated_client_file);
        fputs(" ", translated_client_file);
        token = strtok_r(NULL, " \t\n", dummystatus);
    }
    fputs("\n", translated_client_file);
}
fclose(client_file);
}
void *do_work(void * p) {
  struct tparam * param = (struct tparam *)p;

  while(qfilled != 1);//wait for queue to be filled

  int cindex;
  while(1){
      //check for more clients
  pthread_mutex_lock(&mutex);
  if(qout >= qin){
    pthread_mutex_unlock(&mutex);
    break;
  }
  //process client
  cindex = qout;
  printf("Thread %d is handling client %s\n",param->tid, queue[cindex][1]);
  qout++;
  pthread_mutex_unlock(&mutex);

  char filepath[161];
  if(queue[cindex][0][strlen(queue[cindex][0])-1] == '\n')
      strncpy(filepath,queue[cindex][0],strlen(queue[cindex][0])-1);
  else
    strcpy(filepath,queue[cindex][0]);
  translate(filepath);
  printf("Thread %d finished handling client %s\n",param->tid, queue[cindex][1]);

      //usleep(rand()%100000+10000);
  }
  pthread_exit(NULL);
}

void addDicEntry(char line[]){
char * first = strtok_r(line, " \t", dummystatus);
char * second = strtok_r(NULL, " \t", dummystatus);
char englishWord[161];
if(1==1 || second != NULL)
{
    strcpy(dic[dic_size][0], first);
    strncpy(englishWord, second, strlen(second)-1);
    englishWord[strlen(second)-1] = '\0';
    strcpy(dic[dic_size][1], englishWord);
    dic_size++;
}
}

int main(int argc, char *argv[]) {

srand(time(NULL));
  if(argc < 2){
printf("No dictionary file provided\n");
exit(1);
  }
  //read dictionary
  int i;
  for(i = 0; i < 10; ++i)
dummystatus[i] = (char*)malloc(10);

  FILE * dic_file = fopen(argv[1],"r");
  if(dic_file == NULL)
 {
printf("Dictionary file does not exist\n");
exit(1);
  }
  char line [161];
  char * tmpPtr;
  while((tmpPtr=fgets(line, 160, dic_file))!= NULL) {
if(strcmp(line,"\n") == 0 || strcmp(line,"") == 0 || line == NULL)
    break;
addDicEntry(line);
  }
  fclose(dic_file);
  //End read dictionary

  //Creating threads
  if(argc >= 3)
NTHREADS = atoi(argv[2]);

  pthread_t * threads = (pthread_t *)malloc(NTHREADS*sizeof(pthread_t));
  pthread_attr_t attr;

  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  for (i=0; i<NTHREADS; i++) {
struct tparam * param = (struct tparam *)malloc(sizeof(struct tparam *)*1);
param->tid = i+1;
//printf("Thread %d is being created\n",param->tid);
pthread_create(&threads[i], &attr, &do_work, param);
  }
 //End creating threads

  //insert clients in Q
  FILE * clients_file = fopen("clients.in","r");

  char cid_str[10];
  while((tmpPtr=fgets(line, 160, clients_file))!= NULL) {
if(strcmp(line,"\n") == 0 || strcmp(line,"") == 0 || line == NULL)
    break;
pthread_mutex_lock(&mutex);
strcpy(queue[qin][0],line);
sprintf(cid_str, "%d", qin+1);
strcpy(queue[qin][1],cid_str);
qin++;
pthread_mutex_unlock(&mutex);
  }
  fclose(clients_file);
//for (i=0; i<qin; i++)
//printf("%s\n", queue[i][0]);
  qfilled = 1;
  printf("Q Filled\n");
  //End insert clients in Q

  //printf("Waiting for Threads\n");
  for (i=0; i<NTHREADS; i++)
pthread_join(threads[i], NULL);
  //printf("Threads Finished\n");

  pthread_attr_destroy(&attr);
  pthread_exit(NULL);
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*ler 6

我怀疑这个问题比'覆盖你的字符串'更微妙; 它更多的是覆盖输出线上的数据.试试这段代码:

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

void translate(char* filepath)
{
  char output_filepath[181];

  strcpy(output_filepath, filepath);
    printf("%s\n", output_filepath);      //this prints out "client1.txt" which is correct
  char* ptr = strcat(output_filepath, ".translated");
    printf("%s\n", output_filepath);      //this prints out ".translated" which is wrong
    printf("%s\n", ptr);                  //also prints out ".translated" wrong again
}

int main(void)
{
    translate("client1.txt\r");
    return(0);
}
Run Code Online (Sandbox Code Playgroud)

Mac OS X 10.7.3上的输出:

client1.txt
.translated
.translated
Run Code Online (Sandbox Code Playgroud)

你在文件路径参数字符串的末尾有一个回车符,这导致了这个明显的难题.

您可以通过odhd类似的程序从程序中提供输出.我的召唤odx,但任何事情都会发生(你的程序x39没有任何理由被调用,除非它是一个新的文件名):

$ ./x39 | odx
0x0000: 63 6C 69 65 6E 74 31 2E 74 78 74 0D 0A 63 6C 69   client1.txt..cli
0x0010: 65 6E 74 31 2E 74 78 74 0D 2E 74 72 61 6E 73 6C   ent1.txt..transl
0x0020: 61 74 65 64 0A 63 6C 69 65 6E 74 31 2E 74 78 74   ated.client1.txt
0x0030: 0D 2E 74 72 61 6E 73 6C 61 74 65 64 0A            ..translated.
0x003D:
$
Run Code Online (Sandbox Code Playgroud)

如果我不得不猜测,你client1.txt从Windows框中创建的文件中读取文件名()并使用二进制而不是文本传输转移到Unix,你可能会阅读它,gets()因为这会删除换行符而不是回车符在它之前.

我看到主要代码正在使用fgets()- 好多了gets()! - 但它不具备处理CRLF线路结尾的能力.您的代码不会检查文件名是否已成功打开; 这迟早会导致核心转储(特别是因为磁盘上的输入文件名不太可能以CR结束,'\r'因此open几乎肯定会失败).

  • 在使用文件流指针或文件描述符之前,始终(但始终)检查文件打开功能是否成功.

相信我; 很少你确实会发现一个常规中的错误,因为它被大量使用和测试strcat().