Question

Segmentation fault with string operations - help needed

Asked by: flasht

Hello,
First of all - I am not a C programmer, have no idea about this and it's really hard for me to understand all those memory problems (i'm working on delphi/php).

My problem is that i got 2 long, defined strings:

char * string1 = "something really long (about 1k of characters)"
char * string2 = "something as long or even longer"

Got function:

char *replace_str(char *str, char *orig, char *rep){
  static char buffer[1024];
  char *p;
   
  if(!(p = strstr(str, orig)))
    return str;
      
  strncpy(buffer, str, p-str);
  buffer[p-str] = '\0';
          
  sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig));
            
  return buffer;
}

And what I'm willing to do is to replace few things in string1 and string2 and then marge them to string1 ... it may be important that i need to place length of string2 after all replacements in string1, because its http request and i need content-length.

But every single way i try i get segmentation fault or memory corruption later in program...

My last try was something like this (i know its really sh**tty code but as I said i have no idea what I am doing):

  char dlugosc[32];
  char *dlu = &dlugosc[0];
  char * tempstr;

  itoa (strlen(logindata), dlu);
  tempstr = malloc(sizeof(replace_str(login, "$dlul", dlu)));
  strcpy(tempstr,replace_str(login, "$dlul", dlu));
  login = realloc(login,sizeof(tempstr)+sizeof(logindata));
  strcpy(login,tempstr);
  strcat(login, logindata);
 

It's shorter example where string2 doesnt need to have anything replaced, but it does work neither.

Could anybody help me with that?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-06-02 at 00:28:23ID24455648
Topic

C Programming Language

Participating Experts
3
Points
250
Comments
22

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. malloc
    I have a declaration as below : char **range; Say I have to store 10 strings each having 16 charecters. (I have to decide this dynamically in my program.) How do I allocate memory for this? If I give range = (char **)malloc(10 * 16); It is NOT returning NULL. But if I us...
  2. strcpy() or malloc() problem !!
    hi, i have to tried to create a program which should display n last line from a file specified at command line. here is the code (i called it mylast.c) ###################### #include <stdio.h> #include <stdlib.h> #include <string.h> #include <malloc.h&...
  3. malloc
    I allocate memory to a pointer using malloc or calloc. And then try to assign a value to this array beyond its limit. It still works. Why? eg, int *ptr; ptr = (int *)malloc(5*sizeof(int)); ptr[100] = 5; The above code works. Will not give a crash. Why? Then what is the ...
  4. segmentation fault
    the fllowings is my programs: #include <stdio.h> #define BUFFER_SIZE 1024 int main(void){ FILE *fp; char spp_buf[BUFFER_SIZE]; int length; int line_num; char **spp_line; if((fp = fopen("/root/spp.txt", "r")) == NULL){ ...
  5. segmentation fault on malloc
    Hi, I started using some propritory linux distribution (which is based on RedHat) about three days ago. I have copied some c++ programs which I was working on from my personal RedHat 8.0 machine, but somethings seems to be wrong. The programs compile perfectly but when I ...
  6. Segmentation fault
    Someone can tell me what is wrong in that code? something is work, but half of time I got a Segmentation fault #include <stdio.h> #include <string.h> char *strreplace(char *src, char *replace, char *to) { char *dest = NULL; char *retstr = NULL; ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: evilrixPosted on 2009-06-02 at 00:33:51ID: 24524450

Change...

char * string1 = "something really long (about 1k of characters)"
char * string2 = "something as long or even longer"

to be

char string1[] = "something really long (about 1k of characters)"
char string2[] = "something as long or even longer"

The first form (apart from being deprecated in C++) is a pointer to a const literal in memory, the replacement form will create a copy of the const literal, which is mutable. Trying to perform a replace on a pointer to a const literal is almost certainly your issue.

 

by: Infinity08Posted on 2009-06-02 at 02:16:32ID: 24524851

>>   static char buffer[1024];

You said that the string could be longer than 1kB ... You should probably provide more space for the buffer ...


>>   if(!(p = strstr(str, orig)))
>>     return str;

The function returns two semantically different pointers in different situations. In this case it returns a char*, as a copy of one of the arguments (this might point to anything, including a string literal). In the normal case, a pointer to a static buffer is returned. Be careful with this, as you're making assumptions about the function's usage that aren't necessarily true.


>> sizeof(replace_str(login, "$dlul", dlu))

Since replace_str returns a char*, this will be the same as sizeof(char*). On a 32bit platform for example, that would be 4. It does NOT give you the length of the string - for that you need strlen.


>>   tempstr = malloc(sizeof(replace_str(login, "$dlul", dlu)));
>>   strcpy(tempstr,replace_str(login, "$dlul", dlu));

Note that you're calling replace_str twice here with the same exact parameters ... That's a bit wasteful, especially since you're dealing with large strings.


>>   login = realloc(login,sizeof(tempstr)+sizeof(logindata));

Same comment about sizeof here ...


>>   strcpy(login,tempstr);
>>   strcat(login, logindata);

Does the login string have enough room to hold the concatenation of those two ?



>> But every single way i try i get segmentation fault or memory corruption later in program...

Could you show us the exact code you used, as well as the line where the segmentation fault occurs ?

 

by: Let_Me_BePosted on 2009-06-02 at 03:13:06ID: 24525087

char string[]; is exactly the same as char* string; the correct syntax is const char* string;

In the function. You create an local array buffer. Then use it as a return value. But the array will stop the exist in the exact moment the function will return. Therefore you will get a pointer pointing somewhere into non-valid memory, which will cause access violation when accessing it.

 

by: Infinity08Posted on 2009-06-02 at 03:33:17ID: 24525186

>> char string[]; is exactly the same as char* string

No. The first is an array, while the second is a pointer. They're quite different.


>> In the function. You create an local array buffer. Then use it as a return value.

That's why it's a static buffer ;)

 

by: flashtPosted on 2009-06-02 at 03:33:23ID: 24525188

>>   tempstr = malloc(sizeof(replace_str(login, "$dlul", dlu)));
>>   strcpy(tempstr,replace_str(login, "$dlul", dlu));

> Note that you're calling replace_str twice here with the same exact parameters ... That's a bit
> wasteful, especially since you're dealing with large strings.

Ok... so how do i do it then?

> In the function. You create an local array buffer. Then use it as a return value. But the array
> will stop the exist in the exact moment the function will return. Therefore you will get a pointer
> pointing somewhere into non-valid memory, which will cause access violation when accessing it.

Yes thats why im strcpy'ing it to my string..

 

by: Infinity08Posted on 2009-06-02 at 03:40:43ID: 24525220

>> Ok... so how do i do it then?

Call it once, and save the returned char* somewhere.

But that wasn't the most important part of my post ;) The other problems I pointed out are a lot more damaging.

 

by: flashtPosted on 2009-06-02 at 07:20:02ID: 24527182

void initLoginData(){
  char dlugosc[32]; //10.
  char *dlu = &dlugosc[0];
  char * tempstr;

  itoa (strlen(logindata), dlu);
  tempstr = malloc(strlen(replace_str(login, "$dlul", dlu)));
  strcpy(tempstr,replace_str(login, "$dlul", dlu));
  fprintf(stderr, "ok1");
  login = realloc(login,strlen(tempstr)+strlen(logindata));
  fprintf(stderr, "ok2");
  strcpy(login,tempstr);
  strcat(login, logindata);
}

Still the same ... segmentation fault after ok1, before ok2.

 

by: Infinity08Posted on 2009-06-02 at 07:32:12ID: 24527323

The login string still doesn't have enough room to hold the concatenation of tempstr and logindata. It needs at least one more byte for the trailing '\0'.

You didn't mention whether you fixed the problems in the replace_str function.

You haven't responded to evilrix's comment.


>> segmentation fault after ok1, before ok2.

By simply looking at the output, you can't know that ... The segmentation fault might have occurred after "ok2", even if you didn't see it on the output.
Use a proper debugger to find out the exact location of the segmentation fault (try generating a core dump to analyze eg.).
Alternatively, you could use fflush to make sure that the output buffer is flushed before continuing (ie. after each printf).

You should also check the return values of malloc and realloc, to make sure that allocation succeeded.

 

by: flashtPosted on 2009-06-02 at 07:42:26ID: 24527428

As for evilrix's comment: i said that i'm not performing any operations on result of replace_str function, im strcpy'ing it first to my string. Or maybe thats not what he was reffering to(?).

I changed buffor size to 2048 it's surly enough.

I added 32 to every malloc / realloc

...And it did not help.

void initLoginData(){
  char dlugosc[32]; //10.
  char *dlu = &dlugosc[0];
  char * tempstr;

  itoa (strlen(logindata), dlu);
  tempstr = malloc(strlen(replace_str(login, "$dlul", dlu))+32);
  if(tempstr){
   fprintf(stderr, "tempstr ok\n");
  }
  strcpy(tempstr,replace_str(login, "$dlul", dlu));
  fprintf(stderr, "ok1");
  login = realloc(login,strlen(tempstr)+strlen(logindata)+32);
  if(login){
   fprintf(stderr, "login ok\n");
  }
  fprintf(stderr, "ok2");
  strcpy(login,tempstr);
  strcat(login, logindata);
}

>

tempstr ok
ok1Segmentation fault

 

by: flashtPosted on 2009-06-02 at 08:00:43ID: 24527624

To make sure that this is the function that causes it i modified main to do nothing more, so it cant becaused by anything else:

int main (int argc, char *argv[]){
 
  initLoginData();
  return 0;

}

 

by: Infinity08Posted on 2009-06-02 at 08:14:54ID: 24527810

You haven't showed what 'login' is ... Did you properly initialize it to NULL ?
You haven't showed what 'logindata' is ... Does it point to a valid C string ?

 

by: flashtPosted on 2009-06-02 at 08:17:36ID: 24527845

char * login = "something something something something\r\n"
                      "something something something something\r\n"
                      "something something $dlul\r\n";

char * logindata = "something something something something\r\n"
                             "something something something something\r\n"
                             "something something something something\r\n"
                             "something something something something\r\n"
                             "something something something something\r\n"
                             "something something something something\r\n"
                             "something something something something\r\n";

 

by: Infinity08Posted on 2009-06-02 at 08:19:59ID: 24527870

You can't do a realloc on a string literal :)
You can only do a realloc on dynamically allocated memory (returned by either malloc, calloc or realloc) or a NULL pointer.

 

by: flashtPosted on 2009-06-02 at 09:15:18ID: 24528461

Ok then how do i do what i need to do?

 

by: Infinity08Posted on 2009-06-02 at 09:26:48ID: 24528590

>> Ok then how do i do what i need to do?

What do you need to do ?

Why do you need to realloc the login string ?

 

by: flashtPosted on 2009-06-02 at 09:51:31ID: 24528856

I only need to replace some things in those strings and merge them to one

 

by: Infinity08Posted on 2009-06-02 at 10:46:59ID: 24529444

Yes. But you made 'login' a string literal, which means you should not (cannot) modify it. But then you want to modify it ...

If that suits you, you could simply allocate enough memory using malloc, then copy the string literal in there, and let 'login' point to that allocated memory.

 

by: flashtPosted on 2009-06-02 at 11:12:10ID: 24529723

How exactly? As I said, i have no idea about C, it's my first application

 

by: Infinity08Posted on 2009-06-02 at 11:16:30ID: 24529762

Something like :

const char *login_lit = "something something something something\r\n"
                      "something something something something\r\n"
                      "something something $dlul\r\n";
char *login = (char*) malloc(strlen(login_lit) + 1);
strcpy(login, login_lit);
 
/* ... use it */
 
free(login);

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:

Select allOpen in new window

 

by: flashtPosted on 2009-06-02 at 12:35:11ID: 24530595

Is it ok to make something like this?

strcpy(LOGIN,replace_str(LOGIN, "$pass", domain));

i mean using the same variable in first in second parametr?

 

by: Infinity08Posted on 2009-06-02 at 12:47:32ID: 24530725

>> Is it ok to make something like this?

No. The two arguments of strcpy should be non-overlapping strings. And your replace_str function is written in such a way that that is a possibility.

 

by: flashtPosted on 2009-06-03 at 00:56:06ID: 31587708

Thank you for your patience, everything works fine now.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...