【发布时间】:2013-04-29 13:35:02
【问题描述】:
我有一个字符串:“这是一个简单的字符串”
我的目标是找到(使用strstr)“简单”并将其替换为“样本”。
代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (int argc, char *argv[]){
char *str;
char *pch;
int i=0;
if((str=malloc(BUFSIZ))==NULL){
printf("\n\t MEMORY ERROR");
exit(1);
}
if((pch=malloc(BUFSIZ))==NULL){
printf("\n\t MEMORY ERROR");
exit(1);
}
str="This is a simple string ";
pch=str;
while(str[i]!='\0'){
printf("%c",str[i]);
i++;
}
printf(" -1break\n");
while((*pch!='\0')){
printf("%c",*pch);
pch++;
}
printf(" -2break\n");
printf("%s %d %d %d %d\n",str,strlen(str),sizeof(*str),BUFSIZ,(BUFSIZ-strlen(str)));/*OK*/
if((pch=strstr(str,"simple"))!=NULL){
printf("%s \n",pch); **/*OK*/**
while((*pch!='\0')){
printf("%c",*pch);
pch++;
} **/*SEG FAULT*/**
strncpy(pch,"sample",6);
printf("OK\n");
}
printf("%s %d\n",str,strlen(str));
printf("\n");
return 0;
}
输出:
$ ./strstr
This is a simple string -1break
This is a simple string -2break
This is a simple string 24 1 8192 8168
simple string
Segmentation fault
$
问题:
不能用“sample”替换“simple”。
问题:
如果pch 正确指向“simple”的“s”,为什么strncpy 不能替换“sample”的6 个字母?
【问题讨论】:
-
BUFSIZ的值是多少?此外,您通过malloc将内存分配给str和pch,然后很快重新分配内存,因此您在这里泄漏了内存。 -
-1。另一个类型的问题:
char* var="hello world"; strcpy(var,"hello universe");ORchar* var="hello world"; var[5]=a; -
anishane 这就是我试图理解 strcpy 和 var[5]=a 之间的区别是什么??
标签: c arrays segmentation-fault printf strstr