Thread: Memory allocation problem

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    8

    Memory allocation problem

    I've got this memory allocation problem, can't seem to figure it out:

    Code:
    #include <ctype.h>
    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    int main()
    {
    
    char buf[10];
    char *p[100];
    int i = 0;
    
    
    while(fgets(buf,sizeof(buf),stdin))
      {
        p[i] = malloc(20);
        p[i] = buf;
        i+=1;
      }
    
     for(i=0; i<3; i++)
      {
         printf("%s",p[i]);
      }
    return 0;
    }
    If I type

    john
    pavel
    vlad

    on the input,
    it prints

    vlad
    vlad
    vlad

    on the output ?

    What am doing wrong ? I don't understand, since I allocate 20 bytes for each spot in the array.

    Can someone help me out ?


    thanks

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Code:
    while(fgets(buf,sizeof(buf),stdin))
      {
        p[i] = malloc(20);
        p[i] = buf;
        i+=1;
      }
    You're allocating memory for p[i], but then you're immediately throwing that pointer away by reassigning p[i] to point to buf, so in the end, every element of p ends up pointing to the same buf. Instead, use strcpy() to to copy the contents of buf to the memory you just allocated:
    Code:
    while(fgets(buf,sizeof(buf),stdin))
      {
        p[i] = malloc(20);
        strcpy(p[i], buf);
        i+=1;
      }
    If you understand what you're doing, you're not learning anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with custom dynamic memory allocation routines
    By BLauritson in forum C++ Programming
    Replies: 12
    Last Post: 03-11-2010, 07:26 AM
  2. Problem with memory allocation
    By soulwarrior89 in forum C Programming
    Replies: 23
    Last Post: 07-14-2009, 03:17 PM
  3. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  4. Relate memory allocation in struct->variable
    By Niara in forum C Programming
    Replies: 4
    Last Post: 03-23-2007, 03:06 PM
  5. Pointer's
    By xlordt in forum C Programming
    Replies: 13
    Last Post: 10-14-2003, 02:15 PM