new to c .. function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jabirahmed
    New Member
    • Jun 2007
    • 5

    new to c .. function

    #include <stdio.h>
    char *x(void){
    char *c;
    strcpy(c,"test" );
    printf("%s",c);
    return (c);

    }

    int main(void){
    char *p;
    p=x();
    printf("%s",p);
    return 1;
    }

    -bash-2.05b$ !g
    gcc func.c
    -bash-2.05b$ ./a.out
    Segmentation fault (core dumped)


    Any Idea?

    Thanks

    Jabir
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Yep; in your function 'x' your pointer 'c' doesn't point to anything.

    kind regards,

    Jos

    ps. Use code tags for your code; as it is now it's hardly readable.

    Comment

    • jabirahmed
      New Member
      • Jun 2007
      • 5

      #3
      Originally posted by JosAH
      Yep; in your function 'x' your pointer 'c' doesn't point to anything.

      kind regards,

      Jos

      ps. Use code tags for your code; as it is now it's hardly readable.

      can you help me debug

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by jabirahmed
        can you help me debug
        There's no need to debug; I already found the bug for you; now you fix it.

        kind regards,

        Jos

        Comment

        • edwardrsmith
          New Member
          • Feb 2008
          • 62

          #5
          What he means is that you need to assign the pointer to a location in memory. Try looking up malloc in google. That should give you a lot of good resources. However, the short of it is that a pointer "points" to a location in memory which means that it stores 4 bytes of data on most systems. Right now it is not pointing to any memory. By using malloc you assign a location in memory for that variable to use. It is used like

          Code:
          c = (char*)malloc(sizeof(char)*size);
          In this case size is the maximum length the string can be. It is also important to note that you then have to use free when you are done with the pointer. Again, I would look it up on google but it is used like

          Code:
          free(c);
          If you forget to free the memory you will end up with a memory leak which is bad news all around.

          Edward

          Comment

          • donbock
            Recognized Expert Top Contributor
            • Mar 2008
            • 2427

            #6
            Code:
            #include <stdio.h>
            
            char *x(void) {
                char *c;             // Declare a pointer to char.
                strcpy(c,"test");  // Copy "test" to where c is pointing at.
                printf("%s",c);    // Print the string found where c is pointing at.
                return (c);          // Return pointer that points to where c is pointing at.
            }
            
            int main(void){
                char *p;           // Declare a pointer to char.
                p=x();              // Set p to return value of function x.
                printf("%s",p);  // Print the string found where p is pointing at.
                return 1;          // Return.
            }
            I've reformatted your code and added comments. Examine function x. What memory is modified by strcpy; that is, where is c pointing at? This is the point where your program fails, as pointed out by JosAH. However, be careful how you solve that problem.
            1. You could declare an automatic variable array inside function x and then set c to point at that. The problem here is that all automatic variables in function x are deallocated when that function returns. As a result, function x would be returning a pointer to deallocated memory. Having main reference deallocated memory is very bad. Sometimes it leads to obvious failures (program halts); but often it leads to intermittent and mysterious errors.
            2. You could declare a static variable array outside the scope of all functions and set c to point at that. No problem with deallocated memory. What if the array isn't large enough to hold the string being copied by strcpy? I suggest you google "strncpy".
            3. You could follow suggestion #2 above, but what if you have a multi-threaded program and several threads call function x? In this case, each time a thread calls function x it corrupts the static variable array from the point-of-view of the other threads. You could fix this by declaring an automatic variable array inside function main and passing the address and size of that array to function x. As a result, each thread has its own private memory buffer. In this case you especially want to be certain that strcpy doesn't write past the end of the buffer [see strncpy].
            4. You could use malloc to allocate the buffer -- either main could malloc a big buffer and pass it to x, or x could use strlen on the source string and then malloc a buffer of precisely the necessary size (notice that in this case you don't need strncpy). Either way, you want to make sure that somebody somewhere frees the allocated memory when it is no longer needed. It is good practice to use header comments to clearly document which functions allocate memory and which functions free memory to make it easier to review the code for memory leaks.
            5. You use strncpy, but the source string length is exactly the size of the buffer. Review the man page for strncpy. My recollection is that you'll find that the destination buffer is not null-terminated for this case. You'll have to fix that before you try to print the string.
            6. Instead of using strcpy (or strncpy) you could use an initializer to set c to point at a static string. This is the simplest fix, but may not be useful if the point of your exercise is to become familiar with strcpy.

            By the way, you probably want to terminate both of your printf format strings with "\n" so each appears on its own line.

            Cheers,
            Don

            Comment

            Working...